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 Results.

Ordinary errors are handled using the Result type. Results 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 a Result that happens to be Err

  • 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 fault. ...

Get Programming Rust, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.