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 Resultto handle issues that can be resolved andpanic!for conditions that cannot be safely recovered.
- Optionvs.- Result: Use- Optionfor a missing value without an error context, and- Resultwhen 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 unwraporexpectfor 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.