15.1 Introduction to Error Handling
15.1.1 Recoverable vs. Unrecoverable Errors
Runtime errors typically fall into two categories:
- Recoverable Errors: Situations where the program can handle the error and continue execution. Examples include failing to open a file or receiving invalid user input.
- Unrecoverable Errors: Critical issues where the program cannot continue running safely, such as out-of-memory conditions or data corruption.
Distinguishing between recoverable and unrecoverable errors is fundamental to effective error handling and influences how error management strategies are designed.
15.1.2 Rust's Approach to Error Handling
Rust emphasizes safety and reliability, and its error-handling mechanisms reflect this philosophy. Instead of exceptions or unenforced error codes, Rust uses:
- The
Result
Type: For recoverable errors, Rust uses theResult
enum, which requires explicit handling of success and failure cases. TheResult
type is typically used to propagate error conditions back to the call site, allowing the caller to decide how to proceed. - The
panic!
Macro: For unrecoverable errors, Rust provides thepanic!
macro, allowing the program to terminate in a controlled manner.
This approach ensures that errors are managed systematically, enhancing code robustness and reducing the likelihood of unhandled errors.