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







