Panic

Panics in Rust are a mechanism to allow the program to unwind the stack or abort with an error. Panics are an indication of a logic bug in your program, and should never happen otherwise.

Panics are typically triggered by an invocation of the macro. It will cause the current thread to exit and it will print out an error message to stderr. Panics return, the never type, as they never return.

Panicking macros and functions
There are some helper macros that panic with more specific error messages:


 * The and  macros, which indicate that this part of the code hasn't been written yet.
 * The macro which indicates that this branch of the code should never be executed.
 * The, and  macros panic when an assertion fails. These are often used in tests.
 * The, and  macros also panic when an assertion fails. However, they are only executed if debug assertions are enabled. Since they are by default disabled in optimized builds, this is useful if a condition should be true, but you don't want to impact runtime performance. If memory safety is on the line, never use these macros.

Panics are also often caused by calling  or   on an  or. These methods use the  macro behind the scenes. Their difference is that  panics with a specified error message, which makes it easier to track down the bug.

Panics caused by compiler checks
The compiler automatically detects some bugs at runtime and panics if such a bug occurs:


 * When an array index is out of range (e.g. ). This check can't be disabled, because it ensures memory safety.
 * When arithmetic operations overflow (e.g. ). As this is undesired but doesn't cause undefined behavior, this check can be disabled, and is turned off by default in optimized builds.

Panic hooks and handlers
Panicking is implemented using stack unwinding by default. This means that it is possible to catch panics and define custom behaviour on a panic. Do not use this for general-purpose error handling - for that, see.

When you panic, these things happen:
 * 1) The panic hook is run - by default this will print the panic message to stderr.
 * 2) Scopes are exited one by one, running the destructors for all items in scope, until the top-level scope is reached or a scope catches the panic.

The module provides support for registering custom panic hooks and catching panics. The function runs a given closure, returning an error if the closure panics, and the  and  functions allow you to set and get the global panic hook respectively.