15.8 Summary
Rust’s error-handling model ensures you cannot ignore errors by accident, encouraging a culture of explicit error management in every part of a program. The main principles covered in this chapter are:
- Recoverable vs. Unrecoverable Errors: Use
Result
for recoverable situations andpanic!
for truly irrecoverable ones. Option
vs.Result
: UseOption
for the absence of a value, andResult
when an operation might fail and you need to provide error details.- Error Propagation with
?
: Simplify code without compromising explicit error handling. - Combining Multiple Error Types: Use enums, traits (
Box<dyn Error>
), or custom types to consolidate diverse error sources. - Best Practices: Return errors rather than handling them prematurely, provide clear error messages, and reserve
unwrap
orexpect
for cases where failure cannot realistically occur.
By following these guidelines, Rust code achieves high reliability and clarity—a notable improvement over unchecked error codes in C—and ensures that each failure mode is handled deliberately.