Zig-recover - Regain control when a function panics

6 Likes

Proper use of recover is only for testing panic and undefined behavior runtime safety checks.

Do you have an example of how you do this?

2 Likes

Let’s say that foo(0) is designed to panic.

To test that the function panics you can:

test "foo(0) panics" {
     const err = recover.call(foo, .{0}, error.Panic);
     std.testing.expectError(error.Panic, err).
}

For this to work, you need a custom test_runner with a panic handler:

pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace, ret_addr: ?usize) noreturn {
    recover.panicked();
    std.builtin.default_panic(msg, error_return_trace, ret_addr);
}
2 Likes

I see. Thanks, that’s a nice use case.