What Is panic! and When Should I Use It?

The panic! macro stops Rust program execution immediately for unrecoverable errors, used when continuing is unsafe or impossible.

The panic! macro immediately stops execution and unwinds the stack when your program encounters an unrecoverable error. Use it for situations where continuing would be unsafe or impossible, such as invalid input that breaks core logic or missing critical resources.

fn main() {
    let greeting_file = std::fs::File::open("hello.txt")
        .expect("hello.txt should be included in this project");
}

Alternatively, call panic! directly with a custom message to halt execution immediately:

fn main() {
    panic!("Problem opening the file: {error:?}");
}