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 aJoinHandlepanic!: macro to cause a panicjoin: method onJoinHandleto wait for the thread to finishunwrap_or_else: method onResultto handle theErrcasecatch_unwind: function to catch a panic in a threadmatch: to handle theResultreturned bycatch_unwind
Helpful links
More of Rust
- How to replace all matches using Rust regex?
- How to match the end of a line in a Rust regex?
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to use regex captures in Rust?
- How to use binary regex in Rust?
- How to match whitespace with a regex in Rust?
- How to use modifiers in a Rust regex?
- How to use regex to match a group in Rust?
- How to make regex case insensitive in Rust?
See more codes...