Method catch_unwind can be used to handle unwinding panics.
When panic happened , program will terminate.
fn main() {
panic!("hello");
println!("world")
}
Code above , will never reach println! macro. So it will not print world.
We can use catch_unwind method to catch panic and handle it and not terminate program.
use std::panic::catch_unwind;
fn main() {
let result = catch_unwind(|| {
panic!("hello")
});
match result {
Ok(_) => println!("no panic!"),
Err(e) => println!("panic with error: {:?}", e)
}
println!("world")
}
catch_unwind method take a closure as argument, in this closure body, let’s call panic macro to make it panic. catch_unwind method return a result, so we store it to a variable result.
Let’s use match expression to handle that result. First arm’s pattern is Ok, we just print “no panic”. Second arm’s pattern is cause of panic , and let’s print that in the Err.
Last we call println “world”
When we run this code , it will print : hello , then cause of panic ,then world.