Skip to content
CryoCryo home
Stdlibcore

panic_unwind

import std::core::panic_unwind; · source

Catching a panic

type struct PanicInfo {
    msg:  string;
    file: string;
    line: u32;
}
function catch_unwind<T>(f: () -> T) -> Result<T, PanicInfo>;

catch_unwind(f) runs f and turns a panic that unwinds out of it into Err(PanicInfo) instead of letting it reach the process root:

import std::core::panic_unwind;

match (catch_unwind(risky)) {
    Result::Ok(v)     => { /* normal return */ }
    Result::Err(info) => { /* info.msg, info.file, info.line */ }
}

This is what makes destructors run on a panic: by the two-phase unwind contract, a catch is the phase-1 handler that lets every intermediate frame's cleanup pad run its drops in phase 2. Without a catch, an uncaught panic finds no handler and skips phase 2 entirely.

It requires --panic=unwind (or panic = "unwind" in cryoconfig). Under the default abort strategy a panic terminates the process, so there is nothing to catch and calling catch_unwind is a compile error. f is a plain function pointer rather than a capturing closure — bind captured state into a named function, the same as thread::spawn.

The executor uses this at its poll boundary, which is how one task's panic becomes a JoinError::Panicked for its joiner rather than a crash for its siblings.