panic! (Rust)

panic! aborts the current thread with an error message when the program reaches an unrecoverable state. It unwinds the stack (running destructors) and, by default, prints a message and backtrace.

Rust

A panic signals a bug or a situation the program can't recover from — an out-of-bounds index, an arithmetic overflow in debug mode, or an explicit panic!("..."). It is not the normal error-handling mechanism; that role belongs to Result.

Methods like .unwrap() and .expect(msg) on Option/Result panic when they hit None/Err, which is convenient in tests and prototypes but should be avoided where a real error is possible. .expect lets you attach a message explaining the invariant you assumed.

By default a panic unwinds the stack, running each value's Drop so resources are cleaned up, then ends the thread (which usually ends the program). The rule of thumb: return Result for recoverable, expected failures; reserve panic for programmer errors and broken invariants.

Syntax

panic!("something went wrong: {}", detail);

Examples

Rust

fn main() {
    let v = vec![1, 2, 3];
    println!("{}", v[1]);     // fine
    // println!("{}", v[10]); // would panic: index out of bounds
    let n: i32 = "5".parse().expect("not a number");
    println!("{}", n);
}

Output:

2
5

Learn it in a lesson

See also

Back to the Dictionary