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 match the end of a line in a Rust regex?
- How to replace all matches using Rust regex?
- How to use regex lookbehind in Rust?
- How to use regex captures in Rust?
- How to use regex lookahead in Rust?
- How to use regex with bytes in Rust?
- How to use regex to match a double quote in Rust?
- How to perform matrix operations in Rust?
- How to calculate the inverse of a matrix in Rust?
See more codes...