Panic in Rust

use std::fs::File;
use std::panic;

fn main() {
    // We'll use panic! throughout this site to check for
    // unexpected errors. This is the only program on the
    // site designed to panic.
    panic!("a problem");

    // A common use of panic! is to abort if a function
    // returns an error value that we don't know how to
    // (or want to) handle. Here's an example of
    // panicking if we get an unexpected error when creating a new file.
    let _file = File::create("/tmp/file").unwrap_or_else(|error| {
        panic!("Problem creating the file: {:?}", error);
    });
}

In Rust, the panic! macro is used to abort the program and provide an error message. It’s typically used when something unexpected happens that the program can’t handle.

Running this program will cause it to panic, print an error message and backtrace, and exit with a non-zero status.

When the first panic! in main fires, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first panic!.

$ cargo run
thread 'main' panicked at 'a problem', src/main.rs:7:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

If you run with the RUST_BACKTRACE=1 environment variable, you’ll see a more detailed backtrace:

$ RUST_BACKTRACE=1 cargo run
thread 'main' panicked at 'a problem', src/main.rs:7:5
stack backtrace:
   0: rust_begin_unwind
   1: core::panicking::panic_fmt
   2: panic::main
   3: core::ops::function::FnOnce::call_once
note: Some details omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

Note that unlike some languages which use exceptions for handling of many errors, in Rust it is idiomatic to use the Result type for recoverable errors and reserve panic! for unrecoverable errors.