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.
The code snippet below demonstrates how to use the error
type for error handling:
package main import "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) } }
error
type is returned as the second value from the divide
function. In the error case, a custom error message is generated using errors.New
, which is returned.error
(stored in the err
variable) is simply checked for the nil
value. Since an error was encountered, the returned value is not nil
, and so the error is handled as necessary.RELATED TAGS
View all Courses