Chapter 7. Error Handling
I knew if I stayed around long enough, something like this would happen.
George Bernard Shaw on dying
Rustâs approach to error handling is unusual enough to warrant a short chapter on the topic. There arenât any difficult ideas here, just ideas that might be new to you. This chapter covers the two different kinds of error handling in Rust: panic and Result
s.
Ordinary errors are handled using the Result
type. Result
s typically represent problems caused by things outside the program, like erroneous input, a network outage, or a permissions problem. That such situations occur is not up to us; even a bug-free program will encounter them from time to time. Most of this chapter is dedicated to that kind of error. Weâll cover panic first, though, because itâs the simpler of the two.
Panic is for the other kind of error, the kind that should never happen.
Panic
A program panics when it encounters something so messed up that there must be a bug in the program itself. Something like:
-
Out-of-bounds array access
-
Integer division by zero
-
Calling
.expect()
on aResult
that happens to beErr
-
Assertion failure
(Thereâs also the macro panic!()
, for cases where your own code discovers that it has gone wrong, and you therefore need to trigger a panic directly. panic!()
accepts optional println!()
-style arguments, for building an error message.)
What these conditions have in common is that they are allânot to put too fine a point on itâthe programmerâs ...
Get Programming Rust, 2nd Edition 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.