15.7 Summary
Rust’s error-handling strategy is built upon ensuring you never accidentally overlook potential failures. Its key principles include:
- Recoverable vs. Unrecoverable Errors: Employ
Result
to handle issues that can be resolved andpanic!
for conditions that cannot be safely recovered. Option
vs.Result
: UseOption
for a missing value without an error context, andResult
when errors need to carry additional information.- The
?
Operator: Streamline error propagation without sacrificing clarity. - Handling Diverse Error Types: Combine error variants through custom enums, trait objects, or conversion to unify error handling.
- Practical Guidelines: Return errors to the caller, provide actionable messages, and reserve
unwrap
orexpect
for truly impossible failure cases.
By systematically applying these principles, Rust code becomes more robust, safer, and clearer, avoiding the pitfalls often seen in C’s unchecked error returns.