Sub topic 12
Returning Mixed Errors with Box<dyn Error>
This chapter assumes you know Result, the ? operator, and read_line from the earlier chapters. It also assumes you have used str::parse and know what a trait is at a basic level.
The problem: two kinds of failure
Reading a number from the terminal can fail in two ways:
- Reading can fail.
read_linereturns anio::Error. - Parsing can fail.
parse::<u32>()returns aParseIntError.
A function's return type names exactly one error type. If you declare io::Result<u32>, the ? after parse() does not compile. The compiler cannot turn a ParseIntError into an io::Error. You could write your own enum with a variant for each error. For small programs there is a shorter option.
Box<dyn Error>
dyn Error means "any value that implements the Error trait". Box stores that value on the heap, so the size of the return type is the same whichever error is inside. Box<dyn Error> is therefore a single type that can hold either error.
The standard library implements From<E> for Box<dyn Error> for every error type E. The ? operator calls From when it returns early, so each error is converted to the box automatically.
use std::error::Error;
use std::io;
fn read_age() -> Result<u32, Box<dyn Error>> {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let age: u32 = input.trim().parse()?;
Ok(age)
}
fn main() -> Result<(), Box<dyn Error>> {
let age = read_age()?;
println!("Next year you will be {}.", age + 1);
Ok(())
}The first ? can return an io::Error. The second can return a ParseIntError. Both leave the function as Box<dyn Error>.
What main does with the error
When main returns Err, Rust prints the error with its Debug format and exits with a non-zero status. The output looks like Error: ParseIntError { kind: InvalidDigit }. That is fine while you are developing. For users, handle the error yourself and print its Display text.
Adding your own messages
A &str or String converts into Box<dyn Error> with .into(). That lets you report a rule violation without defining a new error type.
use std::error::Error;
use std::io;
use std::num::ParseIntError;
fn read_age() -> Result<u32, Box<dyn Error>> {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let age: u32 = input.trim().parse()?;
if age > 150 {
return Err("that age is not realistic".into());
}
Ok(age)
}
fn main() {
match read_age() {
Ok(age) => println!("Next year you will be {}.", age + 1),
Err(e) => {
if let Some(parse_err) = e.downcast_ref::<ParseIntError>() {
eprintln!("Please type digits only ({parse_err}).");
} else {
eprintln!("error: {e}");
}
}
}
}downcast_ref::<T>() asks the box whether the error inside is a T. It returns Some(&T) if so and None otherwise. This is how a caller recovers the specific error after it has been boxed.
Trade-offs and common errors
- Lost type information. The compiler no longer tells callers which errors are possible. Callers must use
downcast_refor read the message. If callers need to branch on error kinds, define an enum instead. - Heap allocation. Boxing allocates memory when an error occurs. For input code this cost does not matter.
- Missing
Boxinmain. Writingfn main() -> Result<(), dyn Error>fails becausedyn Errorhas no fixed size. Always writeBox<dyn Error>. - Mixed
?andexpect. Pick one style per function. If a function returnsResult, use?so the caller decides what to do.expectpanics instead.
Exercise
A function must read a line from stdin, parse it as an f64, and reject negative numbers with the message "must not be negative". Write its signature and the line that rejects negative values, then say what happens if the user types "abc".
Show answer
The signature is fn read_positive() -> Result<f64, Box<dyn Error>>. After parsing into value, write if value < 0.0 { return Err("must not be negative".into()); }. If the user types "abc", parse::<f64>()? fails with a ParseFloatError, and ? converts it into Box<dyn Error> and returns it to the caller. The negative check never runs.