我正在使用 panic::catch_unwind
引起 panic :
use std::panic;
fn main() {
let result = panic::catch_unwind(|| {
panic!("test panic");
});
match result {
Ok(res) => res,
Err(_) => println!("caught panic!"),
}
}
( Playground )
这似乎工作得很好,但我仍然将 panic 输出到标准输出。我只想打印出来:
caught panic!
代替
thread '<main>' panicked at 'test panic', <anon>:6
note: Run with `RUST_BACKTRACE=1` for a backtrace.
caught panic!
最佳答案
您需要使用 std::panic::set_hook
注册一个panic hook那什么都不做。然后你可以用 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!"),
}
}
作为Matthieu M. notes , 你可以用 std::panic::take_hook
得到当前钩子(Hook)以便以后在需要时恢复它。
另见:
关于exception - 使用 panic::catch_unwind 时抑制 Rust 中的 panic 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35559267/