Preface
Notes on error handling in Rust
Classification of Errors
- Recoverable errors, can be caught and handled
- Unrecoverable errors, will cause the program to crash and cannot be caught
Throwing Exceptions
<err>
: The error message
Handling Exceptions with unwrap Function
- The unwrap function is a method of the Result enum
- The Result type has two possible values
- If the value is
Ok
, it returns the object inside Ok
- If the value is
Err
, it will throw a panic
during runtime, with the parameter of Err
as the argument to panic
1 2 3 4 5 6 7 8 9 10 11
| fn function_name() -> Result<bool, String> { return if true { Ok(true); } else { Err("<err>".to_string()); } }
fn main() { function_name().unwrap(); }
|
Handling Exceptions with expect Function
- The expect function allows custom error messages when handling exceptions
1
| File::open("<src>").expect("<err>");
|
Done
References
Bilibili - Learning for Pay Raise