Essential Go  Suggest an edit

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 errors by returning error values, not raising exceptions.

Go also includes exception handling with panic and recover but it should only be used very rarely.

Errors are values, just like integers or string.

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

You can create your own error 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 error, return nil.

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

You should always check for errors.

A key to writing robust software is checking errors and handling the appropriately.

If you try to read a file and os.Open fails and returns an error, you should check for that and act accordingly. Trying to read from nil file object will crash the program.

  ↑ ↓ to navigate     ↵ to select     Esc to close