Catching panic! when Rust called from C FFI, without spawning threads

徘徊边缘 提交于 2019-12-03 13:22:56
dragostis

As of Rust 1.9.0, you can use panic::catch_unwind to recover the error:

use std::panic;

fn main() {
    let result = panic::catch_unwind(|| {
        panic!("oh no!");
    });
    assert!(result.is_err());
}

Passing it to the next layer is just as easy with panic::resume_unwind:

use std::panic;

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

    if let Err(e) = result {
        panic::resume_unwind(e);
    }
}
Steve Klabnik

Editor's note: This answer predates Rust 1.0 and is no longer necessarily accurate. Other answers still contain valuable information.

You cannot 'catch' a panic!. It terminates execution of the current thread. Therefore, without spinning up a new one to isolate, it's going to terminate the thread you're in.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!