Error Handling
`panic!` vs `Result`, the `?` operator, `unwrap` and `expect`, custom error types, `From` conversions, `Box<dyn Error>`, thiserror and anyhow.
14 questions
JuniorTheoryCommonHow does Rust handle errors without exceptions, and what must a caller do with a Result?
How does Rust handle errors without exceptions, and what must a caller do with a Result?
Expected failures are values: the function returns Result<T, E>, Ok(value) or Err(error), and the caller cannot reach the value without handling both cases via match, ? or a method. Bugs use panic!, which unwinds and stops the thread.
Common mistakes
- ✗Treating
panic!as an exception for ordinary failures: expected failures are returned asErr, and a panic is reserved for bugs - ✗Thinking a
Result<T, E>can be used as aT: the value has to be taken out ofOkand theErrcase handled first - ✗Believing a panic always kills the whole program: it unwinds and stops the thread that panicked
Follow-up questions
- →Why does the compiler warn when a returned
Resultis never used? - →When does a panic end the whole process rather than one thread?
JuniorTheoryCommonWhat does the program print?
What does the program print?
bad
Open full question →Common mistakes
- ✗Expecting
42, as from C'satoior JavaScript'sparseInt:parseaccepts only a string that is a number as a whole, so42agivesErr. - ✗Expecting a panic, like an exception in other languages: a failed
parsereturnsErr, and the program panics only if it callsunwrapon it.
Follow-up questions
- →How would you change the
Errarm to print why the parse failed? - →Why does a line read with
read_linefail to parse until you calltrim()?
JuniorTheoryCommonWhat does the program print?
What does the program print?
Ok(42) true
Open full question →Common mistakes
- ✗Expecting
42 true:doublereturnsOk(n * 2), and{:?}prints aResultwith its variant, so the first value isOk(42). - ✗Expecting
?to panic on the bad input likeunwrap: it returns theErrfromdouble, andis_err()turns it intotrue.
Follow-up questions
- →What does
doublereturn for the inputx, printed with{:?}? - →How would you write
doublewithout?, usingmatch?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
7because the string is a valid number:?needs a function that returnsResultorOption, whatever value turns up at run time. - ✗Expecting
?to panic onErrlikeunwrap: it returns the error from the function, so the function's return type must be able to hold it.
Follow-up questions
- →How would you change the signature of
mainso that the program compiles? - →What does such a
mainprint when the string is not a number?
JuniorTheoryCommonWhat does ? do on Ok and on Err, and what return type does it need from the function?
What does ? do on Ok and on Err, and what return type does it need from the function?
On Ok(v) the expression yields v and execution continues; on Err(e) the function returns Err(From::from(e)) at once. So the function must return Result (or Option, where None exits the same way), or the compiler stops with E0277.
Common mistakes
- ✗Thinking
?handles the error: it only returns it to the caller, which has to deal with it - ✗Using
?in a function that returns(), such as a plainfn main(): the early return needs aResultorOptionreturn type (E0277) - ✗Expecting
?to panic onErrlikeunwrap: it returns from the function instead
Follow-up questions
- →What does the
From::fromcall inside?let you do with error types? - →How do you apply
?to anOptioninside a function that returnsResult?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It compiles and panics
Open full question →Common mistakes
- ✗Expecting
0, as fromunwrap_or(0):unwraphas no fallback, and onErrit panics withcalled `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }. - ✗Expecting a compile error because
xis plainly not a number: the compiler checks types, andparsereads the text only at run time.
Follow-up questions
- →How would the panic message change if
unwrapwere replaced withexpect? - →With which exit code does the program end after this panic?
JuniorTheoryCommonWhat does the program print?
What does the program print?
0
Open full question →Common mistakes
- ✗Expecting a panic because of
unwrapin the name:unwrap_orreturns its argument onErrand never panics. - ✗Expecting a compile error without
parse::<i32>(): the annotationlet n: i32already tells the compiler which type to parse into.
Follow-up questions
- →What would the program print if
xwere replaced with7? - →When would you pick
unwrap_or_elseoverunwrap_or?
MiddleTheoryCommonOption vs Result: when is absence an error, and how do ok, ok_or and transpose convert them?
Option vs Result: when is absence an error, and how do ok, ok_or and transpose convert them?
Option fits normal absence, like a lookup with no match; Result fits failure, with Err saying why. ok() drops the error, ok_or(e) and lazy ok_or_else(f) turn None into Err, and transpose swaps Option<Result> and Result<Option>.
Common mistakes
- ✗Returning
Optionfor a failure whose cause the caller needs: aResultwith a real error type keeps the reason - ✗Writing
ok_or(build_error())and paying for it on everySome:ok_or_elsebuilds the error only onNone - ✗Confusing
transposewithflatten: it swaps the nesting ofOptionandResultrather than removing a layer
Follow-up questions
- →How do
ok_orand?work together inside a function that returnsResult? - →When would a lookup return
Result<Option<T>, E>, and what does each layer mean?
MiddleTheoryCommonpanic! vs Result: when does each fit in a library and in an app, and what does a panic stop?
panic! vs Result: when does each fit in a library and in an app, and what does a panic stop?
Return Result for failures a caller can expect and handle, like bad input or I/O, so it decides. panic! is for bugs: a broken invariant or API misuse. A library panics only then; an app may also panic at startup. A panic stops just its own thread.
Common mistakes
- ✗Panicking in a library on bad input: the caller loses the chance to recover
- ✗Treating
panic!as an exception for ordinary errors: expected failures belong inResult - ✗Believing a panic always ends the process: by default it unwinds and stops only the panicking thread
Follow-up questions
- →How does the parent thread learn that a spawned thread panicked?
- →When is the Cargo profile setting
panic = "abort"a reasonable choice?
MiddleTheoryCommonWhat does ? desugar to, how does From convert errors, and why does Box<dyn Error> take any?
What does ? desugar to, how does From convert errors, and why does Box<dyn Error> take any?
expr? is roughly match expr { Ok(v) => v, Err(e) => return Err(From::from(e)) }, so an error converts if the function's error type implements From for it. std implements From<E> for Box<dyn Error> for every E: Error, so any error fits.
Common mistakes
- ✗Expecting
?to convert an error with no matchingimpl From: the compiler stops with E0277,`?` couldn't convert the error - ✗Thinking
Box<dyn Error>keeps the concrete type visible to callers: they can recover it only at run time withdowncast_ref - ✗Writing
map_errat every call when oneimpl Fromper source error type lets?convert it
Follow-up questions
- →Why can't one
From<ParseIntError>impl serve two variants that both wrap that error? - →What does a caller lose when a library returns
Box<dyn Error>?
MiddleDesignCommonYour team maintains two crates: geo-parse, a library other teams use to read coordinate files, and geo-cli, an internal command-line tool built on it. Both return Box<dyn Error> today. Library users complain that they cannot tell a malformed file from an unsupported format without comparing message text, and the tool prints invalid digit found in string with no hint of which file or line failed. You may add the error-handling crates thiserror and anyhow. Constraints: the library's public API must let callers branch on each failure case and must not tie them to a particular error-reporting crate; the tool needs messages that show what it was doing when the error happened, down to the root cause. Which crate goes where, why does the library expose a concrete error type, and how do you attach context to an error as it propagates?
Your team maintains two crates: geo-parse, a library other teams use to read coordinate files, and geo-cli, an internal command-line tool built on it. Both return Box<dyn Error> today. Library users complain that they cannot tell a malformed file from an unsupported format without comparing message text, and the tool prints invalid digit found in string with no hint of which file or line failed. You may add the error-handling crates thiserror and anyhow. Constraints: the library's public API must let callers branch on each failure case and must not tie them to a particular error-reporting crate; the tool needs messages that show what it was doing when the error happened, down to the root cause. Which crate goes where, why does the library expose a concrete error type, and how do you attach context to an error as it propagates?
The library uses thiserror: #[derive(Error)] on an enum, with #[error] messages and #[from] conversions, so callers match variants and no reporting crate leaks into its API. The tool uses anyhow: anyhow::Result plus .context() per step.
Common mistakes
- ✗Putting
anyhow::Errorinto a library's public API, so callers can no longer match on the failure cases - ✗Returning
Box<dyn Error>from a library and making callers compare message strings - ✗Propagating with a bare
?in the application and losing which file or step failed
Follow-up questions
- →How does
#[error(transparent)]differ from wrapping an error with a message of its own? - →How do you print the whole cause chain of an
anyhow::Erroron one line?
MiddleTheoryCommonWhy are unwrap and expect a smell in production code, when are they fine, and how do you fix them?
Why are unwrap and expect a smell in production code, when are they fine, and how do you fix them?
Both panic on Err or None, so an expected failure such as bad input becomes a crash. They fit tests, prototypes and invariants the code guarantees, where expect says why. In review, make the function return Result and pass errors up with ?.
Common mistakes
- ✗Treating
expectas a safeunwrap: it panics the same way, only with a clearer message - ✗Rewriting each
unwrapas amatchwithpanic!: the function should returnResultand pass the error up with? - ✗Banning
unwrapin tests too, where a panic is exactly how a test reports failure
Follow-up questions
- →Which lints of the official linter Clippy forbid
unwrapandexpectoutside tests? - →When is
unwrap_or_elsea better fallback thanunwrap_or?
MiddleDesignOccasionalYou are writing a library function parse_config(path) that reads a file and turns lines like port=8080 into a Config struct. It can fail in three ways: the file cannot be read (std::io::Error), a value is not a number (ParseIntError), or a required key such as port is missing. Constraints: callers must be able to react to each case differently (for example, fall back to a default port when the key is missing), log a readable message and reach the underlying cause; the function body uses ? on every fallible call, with no match per call; the library may not depend on third-party crates. Define the error type, say which traits it implements and how ? converts the underlying errors, and when a plain Box<dyn Error> would be enough instead.
You are writing a library function parse_config(path) that reads a file and turns lines like port=8080 into a Config struct. It can fail in three ways: the file cannot be read (std::io::Error), a value is not a number (ParseIntError), or a required key such as port is missing. Constraints: callers must be able to react to each case differently (for example, fall back to a default port when the key is missing), log a readable message and reach the underlying cause; the function body uses ? on every fallible call, with no match per call; the library may not depend on third-party crates. Define the error type, say which traits it implements and how ? converts the underlying errors, and when a plain Box<dyn Error> would be enough instead.
An enum with variants Io(io::Error), BadNumber(ParseIntError) and MissingKey(String), with Debug, Display and Error impls and source() returning the cause. From impls let ? convert. Box<dyn Error> suffices if callers only report.
Common mistakes
- ✗Returning
Stringerrors, which callers can only compare as text instead of matching on a variant - ✗Repeating the wrapped error's text in
Displaywhile also returning it fromsource(), so the printed chain shows it twice - ✗Implementing
ErrorwithoutDebugorDisplayand hitting E0277: the trait requires both
Follow-up questions
- →How would the derive-macro crate
thiserrorshorten this error type? - →Why does
source()returnOption<&(dyn Error + 'static)>with that'static?
SeniorTheoryOccasionalHow does a panic unwind, what do catch_unwind and UnwindSafe do, and what happens at extern "C"?
How does a panic unwind, what do catch_unwind and UnwindSafe do, and what happens at extern "C"?
Unwinding runs Drop for every live value up the stack and stops only that thread; with panic = "abort" the process dies at once. catch_unwind turns a panic into Err and wants an UnwindSafe closure (or AssertUnwindSafe). A panic leaving extern "C" aborts; "C-unwind" lets it cross.
Common mistakes
- ✗Using
catch_unwindastry/catchfor ordinary errors: it belongs at thread-pool and FFI edges and cannot catch an abort - ✗Expecting destructors to run under
panic = "abort": the process ends at once, and buffered output is not flushed - ✗Repeating that a panic across
extern "C"is UB: since Rust 1.81 it aborts the process, and"C-unwind"lets it cross on purpose
Follow-up questions
- →Why does a second panic during unwinding, for example inside
Drop, abort the process? - →How does mutex poisoning relate to unwind safety?