There is no try catch statement in Rust. The closest approach is the ?
operator.
However, you do not have to create a function and a match
statement to resolve it in the end. You can define a closure in your scope and use ?
operator inside the closure. Then throws are held in the closure return value and you can catch this wherever you want like following:
fn main() {
let do_steps = || -> Result<(), MyError> {
do_step_1()?;
do_step_2()?;
do_step_3()?;
Ok(())
};
if let Err(_err) = do_steps() {
println!("Failed to perform necessary steps");
}
}
Playground
Is it possible to handle multiple different errors at once instead of individually in Rust without using additional functions?
There is a anyhow crate for the error management in Rust mostly recommended nowadays.
As an alternative, There is a failure crate for the error management in Rust. Using Failure
, you can chain, convert, concatenate the errors. After converting the error types to one common type, you can catch (handle) it easily.