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

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


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);    }}


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.