Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

error
handling
golang

How to handle errors in Golang

Educative Answers Team

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.

svg viewer

Code

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)
  }
}

Explanation

  • Note the function definition on line 55 where the 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.
  • In the main function, the 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

error
handling
golang
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring