Error handling in Rust: Result all the way down

No exceptions, no surprises. Result, the question mark and how to design your own error types.

Error handling in Rust: Result all the way down

Rust has no exceptions. A function that can fail says so in its return type, and the caller must deal with it. At first, this feels like extra work. After a month, code in other languages starts to look as if it is hiding something.

Every function that can fail says so in its signature.
Every function that can fail says so in its signature.

Two kinds of failure

Rust separates failures you expect from failures that mean the program is wrong.

  • A file is missing, a request times out, the user types a letter where a number should be. These are normal, and you handle them with Result.
  • An index is out of range, or a value that must exist does not. These are bugs, and the program stops with a panic!.

Do not use panics for things that can happen in normal operation. Do not use Result for things that can never happen.

Great! Check your inbox and click the link to confirm.