expression

Contain unwinding panic before a C ABI boundary

Catch an unwinding Rust panic inside a C ABI function and translate it to a documented error. This example exercises the success path only. catch_unwind cannot catch panic=abort, and a panic hook runs before catching. A general boundary must also account for panic payload destruction, state recovery and foreign exceptions. Expected stdout (not executed): 42 Common mistake: Assuming catch_unwind catches aborting panics or arbitrary foreign exceptions.

Formal Syntax & Structure

rust syntaxrust
std::panic::catch_unwind(|| work())

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    use std::ffi::c_int;    extern "C" fn guarded() -> c_int {        match std::panic::catch_unwind(|| 42) {            Ok(n) => n,            Err(payload) => { std::mem::forget(payload); -1 }        }    }    println!("{}", guarded());}
Rust Reference