Essential Go  Edit on GitHub      File Issue

Error handling

Basic error handling:

func sqrt(n float64) (float64, error) {
	if n < 0 {
		return 0, fmt.Errorf("invalid argument '%f', must be >= 0", n)
	}
	return math.Sqrt(n), nil
}

func printSqrt(n float64) {
	if res, err := sqrt(n); err == nil {
		fmt.Printf("sqrt of %f is %f\n", n, res)
	} else {
		fmt.Printf("sqrt of %f returned error '%s'\n", n, err)
	}

}

func main() {
	printSqrt(16)
	printSqrt(-16)
}
sqrt of 16.000000 is 4.000000
sqrt of -16.000000 returned error 'invalid argument '-16.000000', must be >= 0'

Important notes about error handling:

Unlike languages like C# or Python, Go handles errors by returning error values, not raising exceptions.

Go also includes exception handling with panic and recover but it’s not supposed to be used frequently.

Errors are values, just like integers or string.

Type error is a built-in interface which implements Error() string method.

You can use your own types as error values by implementing Error() string method or you can use errors.New(msg string) or fmt.Errorf(format string, args... interface{}) from standard library.

To indicate no errors, return nil.

If a function returns errors, it should always be the last returned value.

Often you want to propagate error value up to the caller until a point in your code where you want to handle it.

You should always check for errors.

You can often see people asking on mailing lists or StackOverflow why their code doesn’t and it would be obvious if the code didn’t skip error checking.

  ↑ ↓ to navigate     ↵ to select     Esc to close