Errors in Go

Knowledge Videos

Short animated explainers, organised by subject.

Errors in Go

A function that can fail returns an error as a second value. nil means success, and you check it with if err != nil, instead of an error jumping out like in JavaScript.

Transcript

Some things can fail: reading a file, or turning the text a b c into a number. In Go, a function that can fail returns two values: the result, and an error.

If the error is nil, nothing went wrong. If it is not nil, something did. The usual code is: if err is not equal to nil, handle it.

Handling it can mean printing a message, returning the error to the caller, or asking the user again. What you must not do is ignore it.

In JavaScript, an error is thrown and jumps out of the function. In Go, an error is a plain value that you check right where it happens.

Remember: a function that can fail returns an error. Nil means all is well, and you check the error with if err not equal to nil.

More in this series