Error Handling in Rust
by Hexagon, 3 min read rust guide
Rust has no exceptions. Instead, functions that can fail say so in their return type, and the compiler makes sure the caller deals with it. In this article, we'll look at panics, the Result type, the question mark operator, and how to make your own error types.
Two Kinds of Errors
Rust splits errors into two groups:
- Unrecoverable errors are bugs, situations that should never happen. The program stops with a panic.
- Recoverable errors are things that can go wrong in normal use: a missing
file, a network timeout, a user typing "abc" where a number was expected.
These are returned as values, with the type
Result.
Panics
A panic stops the current thread, prints a message, and in most programs, ends
the whole program. You've already seen a few things that panic: reading outside
an array, integer overflow in debug builds, and unwrap() on a None. You can
also panic yourself:
Use panics for bugs, not for things a user could cause. If a panic happens,
something in your code needs fixing. Run with RUST_BACKTRACE=1 cargo run to
see exactly where it came from.
Result
Result is an enum, much like Option:
You've seen it already, when parsing numbers:
This prints:
Got the number 42
'abc' is not a number: invalid digit found in string
Just like with Option, you can't use the value without handling the error
case. There's no way to forget a try/catch, as there's nothing to catch.
The error is right there in the type.
Returning a Result
Let's go back to the division function from the article about functions, which
returned 0.0 for division by zero. With Result, it can say what went wrong:
The Question Mark Operator
Imagine a function that does several things that can fail, one after another.
Handling each Result with a match gets long fast. The ? operator does it
for you:
- If the
ResultisOk,?takes the value out, and the function continues. - If it's
Err,?returns the error from the function, right away.
use ParseIntError;
? is a lot like await in JavaScript, in that it's a small mark that does a
lot of work. And just like with await, you can see every place where the
function might stop early.
? only works in a function that returns a Result (or an Option, for
Option values). That includes main, which can return a Result too:
use fs;
If any step fails, the program ends, and prints the error.
Unwrap and Expect
Sometimes, handling every error is more than you need:
They're fine in examples, tests and quick scripts, and when you know the value
is valid, like above. In real code, prefer ? or a match. A good rule is to
use expect over unwrap, and write the message as what you expected to be
true. When it panics, the message tells you which assumption was wrong.
Your Own Error Types
String errors are fine to start with, but the caller can't easily tell
different errors apart. For that, use an enum:
use fmt;
// Display decides how the error looks when printed with {}
// This marks LoginError as a proper error type
impl fmt::Display for LoginError implements a trait, which we'll explain in
the article about traits. For now, think of it as filling in a form that tells
Rust how to print your type.
The caller can now handle each error differently, like the "Try again" above, and the compiler makes sure no variant is forgotten.
Mixing Error Types
What if a function does several things, that fail with different error types?
The simplest answer is Box<dyn std::error::Error>, which means "any kind of
error":
use Error;
? converts each error into a Box<dyn Error> automatically. This is great
for applications and scripts. In libraries, where callers want to tell errors
apart, an enum like LoginError is the better choice.
Two popular crates (Rust's word for packages) make this easier:
thiserror writes the Display code for
your error enums, and anyhow is a more
capable version of Box<dyn Error> for applications. We'll look at how to add
crates in a later article.
Conclusion
Errors in Rust are just values, and the type system makes sure they're handled.
It feels like more work at first, compared to try/catch. But you'll find
that Rust programs rarely crash with errors that nobody thought about, because
the compiler made you think about them.
- Use
panic!for bugs. - Use
Resultfor things that can go wrong. - Use
?to pass errors up to the caller. - Use
Optionfor values that might be missing.