Sub topic 10
Box<dyn Error> for quick, flexible error handling
This chapter assumes you know Result, the ? operator, the From trait, and how to write a custom error enum with Display and Error implementations. You should also be comfortable with the basics of traits and ownership.
The problem with many error types
A function that calls several fallible operations often meets several error types. Reading a file produces an io::Error. Parsing a number produces a ParseIntError. The ? operator can only convert errors with From, and a function has one declared error type.
A custom enum solves this, but it takes a variant, a Display arm, and a From impl for each new error source. For a small tool or a prototype, that is a lot of code. Box<dyn Error> is the shortcut.
What Box<dyn Error> is
dyn Error is a trait object. It stands for any type that implements the std::error::Error trait, with the concrete type decided at runtime. Trait objects have no fixed size, so you keep one behind a pointer. Box puts the error on the heap and gives you a pointer of known size.
The standard library provides this conversion:
impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a>Because of this impl, ? works with every error type that implements Error. The conversion happens automatically at each ?, using the same From mechanism you saw earlier.
A worked example
This function mixes two error types and needs no custom enum:
use std::error::Error;
use std::fs;
fn read_count(path: &str) -> Result<u32, Box<dyn Error>> {
let text = fs::read_to_string(path)?;
let count: u32 = text.trim().parse()?;
Ok(count)
}
fn main() {
match read_count("count.txt") {
Ok(n) => println!("count = {n}"),
Err(e) => println!("failed: {e}"),
}
}The first ? converts an io::Error. The second converts a ParseIntError. Both become Box<dyn Error>.
Creating errors from strings
You can also build a boxed error from a message. Both &str and String convert into Box<dyn Error>:
use std::error::Error;
fn check_age(age: i32) -> Result<i32, Box<dyn Error>> {
if age < 0 {
return Err("age cannot be negative".into());
}
if age > 150 {
return Err(format!("age {age} is unrealistic").into());
}
Ok(age)
}Use .into() on the message. A bare Err("...") does not compile, because &str is not Box<dyn Error>.
Inspecting the error afterwards
Once the type is erased, callers cannot match on variants. You can still try to recover the concrete type with downcast_ref:
use std::error::Error;
use std::num::ParseIntError;
fn describe(e: &Box<dyn Error>) -> &'static str {
if e.downcast_ref::<ParseIntError>().is_some() {
"not a valid number"
} else {
"some other error"
}
}If you find yourself downcasting often, a custom enum is the better design.
Choosing between the two
| Situation | Better choice |
|---|---|
| Small binary, script, or prototype | `Box<dyn Error>` |
| Application code that only reports errors to a user | `Box<dyn Error>` |
| Library with a public API | Custom error type |
| Callers must react differently to each failure | Custom error type |
| Hot path where heap allocation matters | Custom error type |
Trade-offs
- You gain less code and the ability to mix any error type.
- You lose the compiler's help with exhaustive matching, and callers cannot see which errors a function can produce from its signature.
- Each error costs one heap allocation, which rarely matters outside tight loops.
Exercise
A function returns Result<(), Box<dyn Error>>. Inside it you write return Err("disk full");. It fails to compile. What is the fix, and why does the original fail?
Show answer
Write return Err("disk full".into());. The ? operator applies From conversions automatically, but a plain Err(...) expression does not. A &str is not a Box<dyn Error>, so you must call .into() to run the conversion yourself.
Exercise
Why is a custom error enum usually a better choice than Box<dyn Error> for a public library?
Show answer
Callers can match on the enum variants to handle each failure differently, and the function signature documents which errors are possible. With Box<dyn Error> the concrete type is hidden, so callers would have to downcast.