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 use regex with bytes in Rust?
- How to match a URL with a regex in Rust?
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- How to perform matrix operations in Rust?
- How to convert a Rust slice of u8 to a string?
- How do I copy a variable in Rust?
- How to parse a file with Rust regex?
- How to match the end of a line in a Rust regex?
- How to clear a Rust HashMap?
See more codes...