Skip to content

Proposal: Add a way for a test to expect a panic #1356

Open

Description

@mdsteele

When I add safety checks to code (e.g. a panic that fires if the API user violates their end of the API contract), I want to be able to test those safety checks (e.g. by intentionally violating contract in the test, and checking that we get the expected panic). However, there doesn't seem to be any way to catch panics in Zig, even with a custom panic handler (which has to return noreturn, and thus cannot swallow the panic, or otherwise not halt/hang the program, as far as I can tell?), so this kind of testing doesn't seem to be possible. For comparison, Rust tests support this via the #[should_panic(expected = "substr")] annotation.

Some possible proposals:

  1. Add a general mechanism for catching panics. Go has this in the form of recover, and Rust has catch_unwind. Zig could have a builtin to do a similar job. This builtin would be usable anywhere, but explicitly anti-recommended for ordinary error handling.

  2. Provide a test-block-specific way to expect panics. Zig could have a builtin (e.g. @expectPanic(comptime expected_message_substr: []const u8) that would apply to the scope of the test block, and would cause the test to succeed if it panics with a matching message, or fail if it panics with the wrong message or doesn't panic at all.

  3. Don't add this feature at all, and live with the fact that safety checks have to be tested at a higher level (e.g. by running each expect-panic-test as a separate subprocess and expecting that subprocess to crash, e.g. how {#code_begin|test_err|expected message#} in langref.html.in appears to work). Perhaps some mechanism could be added to std.build to make this a bit easier.

My personal preference would be for (2), since that makes the tests very easy to write. If we want (1) as a more general mechanism, then perhaps we could still have (2), or something like it (possibly in userspace), as a convenience. If we don't want to support catching panics, then (3) could work, but I worry that that would make writing safety tests painful enough that library authors would be discouraged from writing them.

Activity

  1. added this to the 0.4.0 milestone on Aug 8, 2018
  2. added
    proposal
    on Aug 8, 2018
  3. andrewrk commented on Aug 8, 2018

    @andrewrk
    Member

    This proposal would have the added benefit of allowing zig to self-host its runtime safety tests: https://github.com/ziglang/zig/blob/master/test/runtime_safety.zig

  4. PavelVozenilek commented on Aug 8, 2018

    @PavelVozenilek

    For tests which call @panic or are rightfully expected to crash, add test annotation (as proposed in #1010 (comment), #567 and #513). Test runner would then fork, invoke just the crashing test and check the exit code. I'd say this is variant of the proposal # 3.

    Do not add any save-me-from-the-crash feature available to the user, that's the road to hell.


    There's use case when you do handle very, very rare situation, but add an assert there, just to make sure that this rare situation doesn't occur by some mistake in your regular code. For this special variant of assert should be invented, as proposed in #1304 (comment). I use not very helpful name assert2 in C.

    Example:

    if (something-almost-impossible-happened) {
       assert2(false); // assert2 does nothing in stress tests, it fires when running ordinary code
       return 0;
    }
    
  5. bronze1man commented on Aug 9, 2018

    @bronze1man

    save-me-from-the-crash feature available to the user

    Please provide only one way to return and cache error.
    Golang's recover feature just make programer process their error with panic and recover which is less code than if xxx return xxx.But you will need to define function with two version, one return error, another panic if error happen. And two version of one functions is the begin of hell.
    But I think zig's error handle is easy enough which can just only use return error.

    Test runner would then fork, invoke just the crashing test and check the exit code.

    Crash process and catch by the parent process should be a good idea.

  6. binary132 commented on Aug 9, 2018

    @binary132

    In my experience panic / recover is not really abused in Go much.

  7. isaachier commented on Aug 9, 2018

    @isaachier
    Contributor

    @binary132, look at how the Go JSON parser cleverly uses recover to handle invalid input errors.

    Edit: Speak of the devil... an article on this topic: https://eli.thegreenplace.net/2018/on-the-uses-and-misuses-of-panics-in-go.

  8. thejoshwolfe commented on Aug 10, 2018

    @thejoshwolfe
    SponsorContributor

    isn't this possible in userspace using setjmp (or equivalent) to effectively create a restore point and then longjmp out of your panic handler? Pretty sure this would never fly at comptime though.

  9. isaachier commented on Aug 10, 2018

    @isaachier
    Contributor

    This relates more to the LLVM IR and how it implements panics. There is definitely a mechanism in the IR to throw and recover from exceptions, but Zig might not want to expose this in the language to avoid abuse.

    Update: More details here: https://llvm.org/docs/ExceptionHandling.html.

  10. modified the milestones: 0.4.0, 0.5.0 on Nov 21, 2018
  11. kristoff-it commented on Apr 24, 2019

    @kristoff-it
    Member

    I think it's fairly common practice in Go to use recover to get a last chance to log remotely the final error message in a program before crashing.

    Without a way to do so, any logging instrumentation added to an executable will not be able to record everything and in some environments it can be a problem if you can't do remote logging properly. An alternative could be to use an external process to do the remote logging (so that it can also read the Zig executable's final message), but it's a nuisance, especially when deploying to a container.

    If there are no bad technical implications, I would recommend leaving the option of using some kind of recover to the user also at run-time, not just for tests, even if the odd json parser library might abuse it.

  12. andrewrk commented on Apr 25, 2019

    @andrewrk
    Member

    Hi Loris, this is not documented yet (See #1517) but you can override the default panic function in the root source file. In the panic function you define what happens when an assertion fails. The default behavior is here: https://github.com/ziglang/zig/blob/56e07622c692f70eb10836b86c5fda02c53e2394/std/special/panic.zig

    If you specify a panic handler in the root source file, like this:

    const builtin = @import("builtin");
    pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn {
        // your implementation here
    }

    Here you can do this logging instrumentation and then call the default panic handler, or do some other strategy.

  13. kristoff-it commented on Apr 25, 2019

    @kristoff-it
    Member

    Oh I see, so, if understand correctly, it can already be done but only at top level, where recover can instead be called at any level.

    Could there be a legitimate reason for a library to want to hide panics?
    I honestly don't know. Food for thought, at least for me.

    Thank you for the clarification :)

  14. thejoshwolfe commented on Apr 26, 2019

    @thejoshwolfe
    SponsorContributor

    It would be rare for a library to handle panics or to expect panics to be handled. such a library would probably advertise itself as a library specifically for managing application state, such as a logging library that "owns" stdout, stderr, and the panic handler. in such a scenario, the library would document that any application that wishes to take advantage of the panic handling code should define a top-level panic handler that calls into the library's implementation.

    The reason there's no library-local support for handling panic is that crash-related situations have app-wide impact, and managing that is the responsibility of the app.

  15. 43 remaining items

  16. matu3ba commented on Apr 20, 2023

    @matu3ba
    Contributor

    it must provide means to recover fully from panic or have ability to eliminate abort side effect

    1. From the top of my mind, I cant think of any, which is not better solved with respawning a process or copy-pasting stack memory + providing shared memory relevant data in a new process image, relevant file descriptors etc (throwing away the rest via letting the Kernel clean up the memory + state).
    2. Without Kernel, you must handle all panics in the first place or you can not recover (unless very specialized device).

    Andrew said, that he had some ideas (for pointer to stack memory, not sure if thats https://gist.github.com/PeyTy/7983dd85026cc061980a6a966bc1afc2), but the overall issue with #782 is that it is unfeasible to compute all possible paths to ensure proper cleanup happens (and its a huge compilation time cost) and then you are stuck with either affine memory ownership semantics (Rust) or linear ones + all the edge cases not handled by such system. Rust for example can introduce memory leaks.

    unless done in conjunction with defer to be called during stack unwinding

    That does not fix the core of the problem: Code, which panics may not have the cleanup handled in any way, because the user could assume the process crashes and the Kernel does the cleanup.

    detect 'bad' code that relies on panics should be available so that user could avoid unexpected abort.
    If Zig is not going to provide proper tools to restore program state after panic, then it would be good to at least have ability to mis-compile if panic is present in code

    1. That sounds very much like static analysis and review. 2. I do agree, that the zig docs could have an explanation for which use cases assertions, checks or panics should be used and to emphasize explaining the structure for use cases crystal clear in the README for potential users (per component). 3. We'll get there eventually.
  17. DoumanAsh commented on Apr 20, 2023

    @DoumanAsh

    Rust for example can introduce memory leaks.

    As users it should be our responsibility to ensure that destructor code doesn't panic which would screw up stack unwinding even further.
    Another important thing is that like in C++ it might be the best have way to detect if stack unwinding is ongoing, but overall I would just recommend not to panic in stack unwinding, or actually all panics should result in aborts if there is already stack unwinding

    That does not fix the core of the problem: Code, which panics may not have the cleanup handled in any way, because the user could assume the process crashes and the Kernel does the cleanup.

    Do you mean that user didn't set up defer?
    Because if defer runs always, regardless of how function exits (normally or due to stack unwinding from panic) it would then let user ensure it runs, but it is up to user to use destructor

    That sounds very much like static analysis and review.

    Not necessary to be stack analysis, but even simplest way to disallow linking panic handler would be nice
    We do not live in ideal world, so if your zig code is entry point you might want to have as much control as possible

  18. jamii commented on Apr 21, 2023

    @jamii

    ability to mis-compile if panic is present in code

    I was hoping that the below might do the trick, but it seems that panic is always referenced. Presumably because it's referenced directly from the compiler rather than by normal mechanisms?

    const std = @import("std");
    
    pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn {
        _ = msg;
        _ = error_return_trace;
        @compileError("panic");
    }
    
    pub fn main() void {}
  19. DoumanAsh commented on Apr 21, 2023

    @DoumanAsh

    Yes, it should not work, compiler should still be able to compile code even if it is never used as it needs to verify validity of your code

    The way I did it in Rust is by introducing destructor function that links invalid item and it would be eliminated during optimization if panic never happened.
    This unfortunately is very bad way to do it so I don't think it is good idea to even try to use it

  20. jamii commented on Apr 21, 2023

    @jamii

    Huh, yeah, that works (EDIT only in release-fast - it still fails to compile in release-safe):

    const std = @import("std");
    
    extern fn extern_panic() void;
    
    pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn {
        _ = msg;
        _ = error_return_trace;
        extern_panic();
        std.os.exit(0);
    }
    
    pub fn main() void {
        //@panic("oh no");
    }

    should still be able to compile code even if it is never used

    @compileError is only an error if it is reachable. Usually a function that contains compileError but is never called is fine. But panic must be special - maybe because it's referenced directly from the compiler, or from some builtin code that is always emitted.

  21. modified the milestones: 0.13.0, 0.12.0 on Jun 29, 2023
  22. loganbnielsen commented on Jan 17, 2025

    @loganbnielsen

    Looks like this hasn't been talked about in a hot minute. Any plans for it still or with the compiler optimizations, async, etc. is this something that we reasonably shouldn't expect for a couple years?

  23. modified the milestones: 0.14.0, 0.15.0 on Jan 25, 2025
  24. added
    enhancement
    and removed
    proposal
    accepted
    on Apr 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions