Chapter 8. Errors
Error handling is one of the biggest challenges for developers moving to Go from other languages. For those used to exceptions, Goâs approach feels anachronistic. But there are solid software engineering principles underlying Goâs approach. In this chapter, weâll learn how to work with errors in Go. Weâll also take a look at panic
and recover
, Goâs system for handling errors that should stop execution.
How to Handle Errors: The Basics
As we covered briefly in Chapter 5, Go handles errors by returning a value of type error
as the last return value for a function. This is entirely by convention, but it is such a strong convention that it should never be breached. When a function executes as expected, nil
is returned for the error parameter. If something goes wrong, an error value is returned instead. The calling function then checks the error return value by comparing it to nil
, handling the error, or returning an error of its own. The code looks like this:
func
calcRemainderAndMod
(
numerator
,
denominator
int
)
(
int
,
int
,
error
)
{
if
denominator
==
0
{
return
0
,
0
,
errors
.
New
(
"denominator is 0"
)
}
return
numerator
/
denominator
,
numerator
%
denominator
,
nil
}
A new error is created from a string by calling the New
function in the errors
package. Error messages should not be capitalized nor should they end with punctuation or a newline. In most cases, you should set the other return values to their zero values when a non-nil error is returned. Weâll ...
Get Learning Go 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.