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[edit | edit source]
There are some helper macros that panic with more specific error messages:
macros, which indicate that this part of the code hasn't been written yet.
macro which indicates that this branch of the code should never be executed.
macros panic when an assertion fails. These are often used in tests.
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
expect() on an
. These methods use the
panic! macro behind the scenes. Their difference is that
expect() panics with a specified error message, which makes it easier to track down the bug.
Panics caused by compiler checks[edit | edit source]
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.
[1, 2]). This check can't be disabled, because it ensures memory safety.
- When arithmetic operations overflow (e.g.
u8::MAX + 1). 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[edit | edit source]
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:
- The panic hook is run - by default this will print the panic message to stderr.
- 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.
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
functions allow you to set and get the global panic hook respectively.