You need to register a panic hook with std::panic::set_hook that does nothing. You can then catch it with std::panic::catch_unwind:
use std::panic;
fn main() {
panic::set_hook(Box::new(|_info| {
// do nothing
}));
let result = panic::catch_unwind(|| {
panic!("test panic");
});
match result {
Ok(res) => res,
Err(_) => println!("caught panic!"),
}
}
As Matthieu M. notes, you can get the current hook with std::panic::take_hook in order to restore it afterwards, if you need to.
See also:
- Redirect panics to a specified buffer