Chapter 9: Error Handling

This commit is contained in:
Zykino 2018-12-02 23:43:00 +01:00
parent 65287400a3
commit a12dfc1927
1 changed files with 42 additions and 0 deletions

View File

@ -10,6 +10,7 @@ fn main() {
chapter_6();
chapter_7();
chapter_8();
chapter_9();
}
fn chapter_1() {
@ -996,3 +997,44 @@ fn hash_maps() {
println!();
}
fn chapter_9() {
unrecoverable_errors_with_panic();
recoverable_errors_with_result();
panic_or_result();
println!();
}
fn unrecoverable_errors_with_panic() {
println!("The `panic!` macro crash the program gracefully. We may configure it to abort instead.");
println!("If we want the stacktrace we need to set the environment variable: `RUST_BACKTRACE`.");
println!();
}
fn recoverable_errors_with_result() {
println!("The `Result` enum enable a function to return a recoverable error.");
println!("We may check for a kind of error by stacking the `match`.");
println!("Instead we may prefer to use closures to better communicate our intention and not use to much nested `match`.");
println!("For example `unwrap` and `expect` are shortcuts to panic on error.");
println!("See chapter 13 for more infos.");
println!("If we want to let the caller take care of the errors we encounter we can propagate the error with `?`");
println!("Fun example (ending with a bit of a cheat): https://doc.rust-lang.org/stable/book/2018-edition/ch09-02-recoverable-errors-with-result.html#propagating-errors");
println!();
}
fn panic_or_result() {
println!("It is ok to panic! when in `Examples, Prototype Code, and Tests`");
println!("For the examples and when prototypying `unwrap` and `expect` are clear markers showing where to handle the errors");
println!("When testing panicking is the way to tell that the test failed");
println!("When we hardcode a value (or have more infos than the compiler)");
println!("We can also panic when the developper using our library break one of our contract.");
println!("Each time we create contract like this we should document them.");
// Example: Trying to access an array/Vec<> after a it's max length (out-of-bounds)
println!();
}