Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
692 views
in Technique[技术] by (71.8m points)

exception - Suppress panic output in Rust when using panic::catch_unwind

I'm using panic::catch_unwind to catch a panic:

use std::panic;

fn main() {
    let result = panic::catch_unwind(|| {
        panic!("test panic");
    });

    match result {
        Ok(res) => res,
        Err(_) => println!("caught panic!"),
    }
}

(Playground)

This seems to work just fine, but I am still getting the output of the panic to stdout. I'd like this to only print out:

caught panic!

Instead of

thread '<main>' panicked at 'test panic', <anon>:6
note: Run with `RUST_BACKTRACE=1` for a backtrace.
caught panic!
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...