Error handling
panic! and unrecoverable errors
Rust has no exceptions. It separates errors into two families. Unrecoverable errors are bugs: an out-of-bounds index, a broken invariant. They trigger a panic!, which stops the thread and prints a message. Recoverable errors are normal situations you must handle: a missing file, a malformed CSV line. They go through the Result type.
rust
fn main() { let scenarios: Vec<f64> = Vec::new(); if scenarios.is_empty() { panic!("aucun scénario : la simulation n'a pas tourné"); }}unwrap() and expect("message") extract the value from an Option or a Result, and panic if there is none. They are useful in tests, prototypes, or when you know an error is impossible. Prefer expect: its message explains why you thought it could not fail.
rust
fn main() { let fixed: f64 = "0.035".parse().expect("taux codé en dur, toujours valide"); println!("{fixed}"); let from_user = "3,5 %"; // let rate: f64 = from_user.parse().unwrap(); // panique : invalid float literal println!("{:?}", from_user.parse::<f64>()); // Err(ParseFloatError { kind: Invalid })}