Rust Reference ยท Errors, Panics and Process
Rust Box<dyn Error>
Reference for Box<dyn Error> in Rust: converting any error with ?, from strings, downcasting to concrete types, Send and Sync variants and trade-offs.
Box<dyn Error> is a boxed trait object that can hold any value implementing std::error::Error. As a function's error type, it lets one Result carry parse errors, I/O errors and your own errors at the same time, with no conversion code: the ? operator boxes each error automatically.
It is the usual choice for main, small tools and application glue code. The price is that callers see only "some error". They can print it or walk its source() chain, but matching on a specific kind requires downcasting.
use std::error::Error; fn run() -> Result<(), Box<dyn Error>> { let n: i32 = "42".parse()?; // ParseIntError becomes Box<dyn Error> println!("{n}"); Ok(()) }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
Box<dyn Error> // not Send or Sync Box<dyn Error + Send + Sync> // can cross threads Box<dyn Error + Send + Sync + 'static> impl dyn Error { pub fn is<T: Error + 'static>(&self) -> bool; pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T>; pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T>; } impl Box<dyn Error> { pub fn downcast<T: Error + 'static>(self) -> Result<Box<T>, Box<dyn Error>>; }
| Conversion | Result |
|---|---|
? on any E: Error + 'static |
E is boxed into Box<dyn Error>. |
"text".into() or String::into() |
A boxed private error whose Display shows the text. |
Box::new(MyError) |
Explicit boxing of your own error type. |
Usage notes
?works because of the standardimpl<E: Error> From<E> for Box<dyn Error>. The same impls exist forBox<dyn Error + Send + Sync>.- Use
Box<dyn Error + Send + Sync>when errors move between threads or are stored in aJoinHandleresult. The plain form is notSend, and the compiler complains in surprising places when you mix them. Box<dyn Error>does not itself implementError, which sometimes blocks generic code that wantsE: Error. If you need that, use a dedicated wrapper type.- A
mainthat returnsResult<(), Box<dyn Error>>prints the error withDebug(Error: ParseIntError { kind: InvalidDigit }) and exits with status 1. - Downcasting is a last resort. If callers need to branch on error kinds, give them an enum (see the custom error page).
- String errors have no
source(). Prefer a real type when the error should expose its cause. - Boxing allocates, but only on the error path, so the cost rarely matters.