Go edit forum

Error handling

Basics of 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'

 

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

Go also provides exceptions with panic and recover but they should be used rarely.

Errors are values, just like integers or string.

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

To indicate success, return nil.

To create an error you can use standard library functions errors.New(msg string) or fmt.Errorf(format string, args... interface{}).

You can also return custom error types by defining structs that implement Error() string method.

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

Always check returned errors. A key to writing robust software is checking errors and handling them appropriately. Beginners often fail to check for errors and are then are faced with debugging mysterious failures.

  ↑ ↓ to navigate     ↵ to select     Esc to close