From a12dfc192718011470c272b736b08bb30d53b1c7 Mon Sep 17 00:00:00 2001 From: Zykino Date: Sun, 2 Dec 2018 23:43:00 +0100 Subject: [PATCH] Chapter 9: Error Handling --- src/main.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/main.rs b/src/main.rs index e243a8a..a54b12d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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!(); +}