Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Macros

Rust panic! macro

Reference for the Rust panic! macro: how it formats a message, unwinding, exit code 101, panic payloads, catching panics and when to prefer Result.

panic! stops the current thread with an error message. It is meant for bugs: states that should be impossible, broken invariants, or a caller who violated a documented contract. For problems that can happen in normal use (bad input, missing files), return a Result instead.

The arguments work like println!: a format string plus values. When a thread panics, Rust prints the message with the file, line and column, then unwinds the stack, running destructors on the way out. If the main thread panics, the process exits with code 101.

Rust
panic!("something is badly wrong: {}", code);

Try it

Rust A panic with a formatted message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Destructors run while unwinding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
panic!();                         // message: "explicit panic"
panic!("literal message");
panic!("value was {}", value);    // format string + arguments
Name Description
format string Same syntax as println!. In edition 2021 and later it must be a string literal.
arguments Values inserted into the message.

Returns: never (the type is !), so it fits anywhere an expression of any type is expected. Effects: by default unwinds the stack; with panic = "abort" in the Cargo profile the process aborts immediately.

Usage notes

  • Exit code 101. A panic in main ends the process with status 101; the message goes to standard error.
  • Other threads. A panic in a spawned thread only ends that thread; join() returns Err carrying the payload.
  • Types. Because panic! has type !, let n: u32 = if ok { 5 } else { panic!("no") }; compiles.
  • Related panics. unwrap, expect, indexing out of range, integer overflow in debug builds, division by zero and RefCell double borrows all panic.
  • Not for expected errors. A library that panics on bad input takes the decision away from the caller. Return Result or Option.
  • Unwind safety. catch_unwind can stop a panic at a boundary (for example before FFI), but it is not an exception system.
  • Backtraces. Set RUST_BACKTRACE=1 in the environment to print the call stack.