exception - 使用 panic::catch_unwind 时抑制 Rust 中的 panic 输出

标签 exception rust

我正在使用 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/

相关文章:

java - Java 是否允许在编译时进行不变性检查?

exception - Powershell WebClient 下载文件异常路径中的非法字符

c++ - 带有 nothrow 选项的 Operator new 仍然抛出异常

rust - 引用通用对象的特征似乎是不可能的

rust - Rust 中的符号 '&' 和星号 '*' 是什么意思?

kotlin - 如何只显示错误而不显示调用堆栈跟踪?

java - 为什么在 .NET 中不检查异常?

rust - Actix actor 的错误处理和条件链接

rust - 如何在不出错的情况下实现Ord特质 “use of unstable library feature ' clip'”?

rust - 如何使用另一个切片作为分隔符来拆分切片?