Go: Errors explained

Go typically uses return values to indicate errors. Multivalued returns makes it easy to return an error value alongside the normal return value.

The os.Open function is a good example:

func Open(name string) (file *File, err error)

which is used as follows:

f, err := os.Open("file.txt")
if err != nil {
	log.Fatal(err)
}
// do something with the open *File f

By convention the built-in error type is used:

type error interface {
    Error() string
}

The error interface requires only an Error method, but specific error implementations often have additional methods, allowing callers to inspect the details of the error.

To create a simple string-only error you can use errors.New as follows:

if problem {
	return errors.New("Houston, we have a problem")
}

Panic

In unrecovorable conditions, due to for instance programming errors, the program can call panic(err). When the program panics, it starts to unwind the call stack. This continues until the stack is empty (at which point the program crashes) or until the recover function is called. Calling panic is similar to throwing an exception in Java or C++, but instead of try/catch blocks, Go uses deferred methods and the recover method.

Comments