liveBook · Manning

Panic

As explained in Learn Rust in a Month of Lunches

A panic is Rust's unrecoverable failure behavior that stops ordinary execution and reports diagnostic information.

A panic stops normal execution when Rust cannot continue as requested. It reports what went wrong and where, including a file, line, and column. For example, indexing a two-item vector at position four panics with an “index out of bounds” message. Rust unwinds the stack as it stops. section 5.2.1 section 6.3

You can also call `panic!` yourself, with a message that makes the problem easier to find. Suppose a function must receive exactly three items. Reading its first three items would still work if someone passed six, hiding a logic bug. A length check makes that mistake visible. section 6.3

fn print_all_three_things(vector: Vec<i32>) {
    if vector.len() != 3 {
        panic!("my_vec must always have three items");
    }
    println!("{}, {}, {}", vector[0], vector[1], vector[2]);
}
 
fn main() {
    let my_vec = vec![8, 9, 10, 10, 55, 99];
    print_all_three_things(my_vec);
}

The length check panics before printing when the vector has six items rather than three. section 6.3

A missing value or an error does not always need to become a panic. Calling `.unwrap()` on `None` or `Err` panics; `.expect()` also panics but supplies your own message. When the case can be handled, match an `Option` or handle a `Result` instead. section 6.3 section 5.2.1

Panic is useful when failure is the behavior you want to check:

  • `assert!` panics if a condition is false; `assert_eq!` and `assert_ne!` panic when their comparisons fail. section 6.3
  • A test marked `#[should_panic]` checks that invalid input causes a panic. For example, a calculator test passes `7 - seven` to a function that accepts only digits, minus signs, and spaces. section 14.3.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains panic messages, source locations, and stack unwinding through examples without developing deeper runtime internals.
Examples
Shows an out-of-bounds vector access, a three-item length guard, and a calculator test that expects invalid input to panic.
What it assumes
Introduces panic in plain language, then uses vectors, Option, and Result to show where it can arise.
What you can do after
Diagnose/debug with panic locations and messages, add panic! guards, and test expected panics with #[should_panic].
How it connects
Connects panic to vector indexing, Option, Result, unwrap, expect, assertions, and testing.

Also explained in

Compare how 8 books explain panic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.