Suppress panic output in Rust when using panic::catch_unwind
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
Use following catch_unwind_silent
instead of regular catch_unwind
to achieve silence for expected exceptions:
use std::panic;
fn catch_unwind_silent<F: FnOnce() -> R + panic::UnwindSafe, R>(f: F) -> std::thread::Result<R> {
let prev_hook = panic::take_hook();
panic::set_hook(Box::new(|_| {}));
let result = panic::catch_unwind(f);
panic::set_hook(prev_hook);
result
}