II
⚠️ Error Handling
Unrecoverable Errors
Concept
Rust distinguishes between unrecoverable errors (bugs that should never happen) and recoverable errors (expected failures like "file not found"). For unrecoverable errors, Rust has the panic! macro. When a program panics it prints an error message and unwinds the stack. You should panic when the program reaches an invalid state that it cannot reasonably recover from.
example.rs
fn divide(a: f64, b: f64) -> f64 {
    if b == 0.0 {
        panic!("Division by zero! a={}, b={}", a, b);
        // Program immediately stops — no way to recover
    }
    a / b
}

fn main() {
    println!("{}", divide(10.0, 2.0));  // 5.0 — fine
    
    let v = vec![1, 2, 3];
    // These also panic:
    // v[99]          — index out of bounds
    // v.unwrap()     — None.unwrap()
    // "abc".parse::<i32>().unwrap() — would need expect() or match
    
    println!("{}", divide(10.0, 0.0));  // PANIC
}
Quick Check

When should you use panic! vs returning a Result?

1 / 2