Chapter 4. Handling errors and panics

This chapter covers

  • Learning the Go idioms for errors
  • Providing meaningful data with errors
  • Adding your own error types the Go way
  • Working with panics
  • Transforming panics into errors
  • Working with panics on goroutines

As Robert Burns famously expressed in his poem “To a Mouse,” “The best-laid schemes o’ mice an’ men / Gang aft agley.” Our best plans often still go wrong. No other profession knows this truth as thoroughly as software developers. This chapter focuses on handling those situations when things go awry.

Go distinguishes between errors and panics—two types of bad things that can happen during program execution. An error indicates that a particular task couldn’t be completed successfully. A panic indicates that a severe event occurred, probably as a result of a programmer error. This chapter presents a thorough look at each category.

We start with errors. After briefly revisiting the error-handling idioms for Go, we dive into best practices. Errors can inform developers about something that has gone wrong, and if you do it right, they can also assist in recovering and moving on. Go’s way of working with errors differs from the techniques used in languages such as Python, Java, and Ruby. But when you correctly use these techniques, you can write robust code.

4.1. Error handling

4.2. The panic system

4.3. Summary

sitemap