Error Handling
Rust has no exceptions. Errors fall into two categories, and the language has a tool for each. An unrecoverable error is a bug in the program itself: indexing past the end of a vector, a broken invariant. The answer to it is a panic!: the thread stops, the stack unwinds, destructors run. A recoverable error is something the program must anticipate: the file is missing, the user typed letters instead of a number, the network did not answer. Such an error is an ordinary value of type Result<T, E>: the function returns Ok(value) or Err(error), and the type forces the caller to handle both cases.
Hence the main difference from exceptions: an error is visible in the function's signature and cannot silently fly through ten levels of calls. The ? operator helps pass it upwards: on Err it returns the error from the function at once, converting it through From on the way. The unwrap and expect methods turn an Err into a panic — fine in tests and prototypes, but in production code it usually means an unhandled case. For your own errors you write an enum with the Display and std::error::Error traits, and applications often reach for Box<dyn Error> or the anyhow crate. This topic walks error handling layer by layer — from panics to error conversion.
Topic map
- Panic: Unrecoverable Errors —
panic!is for bugs, not expected failures; stack unwinding and destructors; a panic stops only its own thread;panic = "abort";RUST_BACKTRACE=1. - The Result Type —
Result<T, E>with theOkandErrvariants; handling it withmatch;parse::<i32>()andParseIntError; the#[must_use]attribute; when to useOptionand whenResult. - The ? Operator — an early return of
Errwith conversion throughFrom::from; works only in a function returningResultorOption, otherwise E0277;?onOption; amainthat returnsResult. - unwrap and expect — a panic on
ErrandNone; when that is acceptable: tests, prototypes, proven invariants;unwrap_or,unwrap_or_else,unwrap_or_default,okandok_or. - Custom Error Types — an error enum with
Debug,Displayandstd::error::Error; a chain of causes throughsource(); the cause's text is not repeated inDisplay. - Error Conversion —
impl Fromfor?;map_errwhen oneFromis not enough;Box<dyn Error>anddowncast_ref; thiserror for libraries, anyhow for applications.
Common mistakes and traps
| Mistake | Consequence |
|---|---|
Calling unwrap() on user input or a file's contents | A panic called `Result::unwrap()` on an `Err` value: … and exit code 101 instead of a clear message |
Using ? in a function that returns () | error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` … |
Applying ? to a ParseIntError in a function returning Result<_, AppError> without impl From | error[E0277]: `?` couldn't convert the error to `AppError` |
Calling a function that returns Result and not looking at the result | The warning unused `Result` that must be used, and the error is lost silently |
| Panicking in a library on invalid input | The caller cannot recover: the decision "crash or not" has been taken away from it |
Expecting a main returning Result<(), Box<dyn Error>> to print the error's text | It prints the Debug form: Error: ParseIntError { kind: InvalidDigit } |
| Assuming a panic in a spawned thread brings down the whole program | Only that thread dies, join() returns Err; the process ends if main panics or panic = "abort" is set |
Why it matters in interviews
Error handling is a mandatory topic of a junior Rust interview: there are no exceptions, and the candidate has to explain what replaces them and why an error in the type beats an error that is "thrown." After that comes practice: reviewing code with unwrap everywhere, designing your own error type, and choosing between thiserror and anyhow.
What interviewers usually check:
- How Rust does without exceptions: recoverable errors are
Result, unrecoverable ones arepanic!, and when to pick which. - What
?does, what it requires of the function's return type, and how it converts errors throughFrom. - Why
unwrapandexpectare dangerous in production code and when they are still acceptable. - How to go from
OptiontoResultand back:ok,ok_or,ok_or_else. - How to design your own error type — an enum,
Display,Error,source(),From— and whenBox<dyn Error>is enough. - What happens on a panic: stack unwinding, destructors, thread versus process,
panic = "abort".