What is a panic in Rust and when does it occur?
Answer
A panic is Rust's mechanism for handling unrecoverable errors — situations where the program cannot continue safely. When a panic occurs, Rust unwinds the stack (running drop handlers), prints an error message with a backtrace (if RUST_BACKTRACE=1 is set), and terminates the thread (or the entire process if it is the main thread). Common causes: calling .unwrap() on a None or Err value, index out of bounds (v[100] when the vec has fewer elements), integer overflow in debug mode, and explicit panic!("message"). In production code, prefer returning Result over panicking. Use std::panic::catch_unwind() to catch panics at a boundary if needed (e.g., in FFI). Configure panic = "abort" in Cargo.toml for smaller binary size at the cost of no stack unwinding.
Previous
What is pattern matching with destructuring in Rust?
Next
How does error handling with the ? operator work in Rust?