rustHow to catch a panic in a Rust thread?
Catching a panic in a Rust thread can be done using the catch_unwind
function. This function will return a Result
type, with Ok
if the thread completed successfully, and Err
if the thread panicked.
use std::thread;
let result = thread::spawn(|| {
panic!("Panic!");
}).join();
let unwind_result = result.unwrap_or_else(|_| {
thread::catch_unwind(|| {
println!("Caught panic!");
})
});
match unwind_result {
Ok(_) => println!("Thread completed successfully"),
Err(_) => println!("Thread panicked"),
}
Output example
Caught panic!
Thread panicked
Code explanation
thread::spawn
: creates a new thread and returns aJoinHandle
panic!
: macro to cause a panicjoin
: method onJoinHandle
to wait for the thread to finishunwrap_or_else
: method onResult
to handle theErr
casecatch_unwind
: function to catch a panic in a threadmatch
: to handle theResult
returned bycatch_unwind
Helpful links
More of Rust
- How to replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to replace strings using Rust regex?
- How to split a string with Rust regex?
- How to use non-capturing groups in Rust regex?
- How to convert a Rust HashMap to a BTreeMap?
- How to implement a generator trait in Rust?
- Bitwise operator example in Rust
- How to set default value in Rust struct
- How to match whitespace with a regex in Rust?
See more codes...