...

/

Error-Handling

Error-Handling

This lesson introduces error-handling in Go.

Introduction

Go does not have an exception-handling mechanism, like the try/catch in Java or .NET. For instance, you cannot throw exceptions. Instead, it has a defer-panic-and-recover mechanism. The designers of Go thought that the try/catch mechanism is overused and that the throwing of exceptions in lower layers to higher layers of code uses too many resources. The mechanism they devised for Go can ‘catch’ an exception, but it is much lighter. Even then, it should only be used as a last resort.

How then does Golang deal with normal errors by default? The Go way to handle errors is for functions and methods to return an error object as their only or last return value—or nil if no error occurred—and for the code calling functions to always check the error they receive.

Note: Never ignore errors because ignoring them can lead to program crashes.

Handle the errors and return from the function in which the error occurred with an error message to the user: that way, if something goes wrong, your program will continue to function, and the user will be notified. The purpose of panic-and-recover is to deal with genuinely exceptional (so unexpected) problems and not with normal errors.

Go makes a distinction between critical and non-critical errors: non-critical errors are returned as normal return values, whereas for critical errors, the panic-recover mechanism is used.

Library routines often return some sort of error indication to the calling function. In the preceding chapters, we saw the idiomatic way ...