How to handle errors in Golang
Error handling in Golang is done through the built-in interface type, error. It’s zero value is nil; so, if it returns nil, that means that there were no errors in the program.
The most common way to handle errors is to return the error type as the last return value of a function call and check for the nil condition using an if statement.
Code
The code snippet below demonstrates how to use the error type for error handling:
package mainimport "fmt"import "errors" // Import the errors package.func divide(x int, y int) (int, error) {if y == 0 {return -1, errors.New("Cannot divide by 0!")}return x/y, nil}func main() {answer, err := divide(5,0)if err != nil {// Handle the error!fmt.Println(err)} else {// No errors!fmt.Println(answer)}}
Explanation
- Note the function definition on line where the
errortype is returned as the second value from thedividefunction. In the error case, a custom error message is generated usingerrors.New, which is returned. - In the main function, the returned
error(stored in theerrvariable) is simply checked for thenilvalue. Since an error was encountered, the returned value is notnil, and so the error is handled as necessary.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved