Chapter 3. Error Handling Recipes
3.0 Introduction
In his An Essay on Criticism, Alexander Pope wrote, “to err is human.” And since software is written by humans (for now), software errs as well. Just like human errors, it’s about how gracefully we can recover from them. That’s what error handling is all about—how we recover when our program gets into a situation we did not expect or cater to in its normal flow.
Programmers often treat error handling as tedious work and an afterthought. That’s generally an error in itself. Just as testing and error handling should be top of mind, recovering from the error should be part of good software design. In Go, error handling is treated pretty seriously, though unconventionally. Go has the errors
package in the standard library that provides many functions to manipulate
errors, but most error handling in Go is built into the language or is part of the idiomatic way of programming in Go. This chapter covers some basic ideas in error handling in Go.
Errors Are Not Exceptions
In programming languages like Python and Java, error handling is done through exceptions. An exception is an object that represents an error, and whenever something goes wrong, you can throw an exception. The calling function usually has a try
and catch
(or try
and except
in Python) that handles anything that goes wrong.
Go does this slightly differently (or entirely differently, depending on how you look at it). Go doesn’t have exception handling. Instead of exceptions, ...
Get Go Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.