Error Handling Flashcards
What are the two major categories Rust groups errors into?
recoverable and unrecoverable.
What does Rust have for recoverable errors?
Result
What does Rust have for unrecoverable errors?
panic!
What happens when the panic! macro executes?
Failure message is printed, stack is unwound and cleaned up, and then program quits.
How can you prevent a program from performing expensive unwinding on panic!
By having it abort instead. Add panic = ‘abort’ to the appropriate profile sections in the Cargo.toml.
What is a backtrace?
A list of all the functions that were called leading to the failure point.
How is the Result enum defined?
enum Result {
Ok(T),
Err(E),
}
What does unwrap() do with the Result type?
Returns the T value inside the Ok if present, else, if an E or None is present then it will panic.
What does the expect() do with the Result type?
Returns the T value inside the Ok if present, else, if an E or None is present will panic! with a user defined message.
Provide an example statement using the expect().
let f = File::open(“hello.txt”).expect(“Failed to open hello.txt”);
What is propagating an error?
Returning an error to the calling code so that it can decide how to handle it.
What is the ? operator in Rust?
A unary suffix operator which can be placed on an expression to unwrap the value on the left hand side of ? while propagating any error through an early return.
What type must a function return if it uses the ? operator?
Result.
When should your code panic?
When it could end up in a bad state:
- Something not expected to happen regularly
- Downstream code relies on the point to be in a good state.
- Not a good way to encode this information in the types used.
When should your code return a Result?
When failure is an expected possibility.