File tree Expand file tree Collapse file tree
courses/rust_essentials/200_error_handling Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -41,11 +41,52 @@ Handling Results
4141
4242:error: `Failed to open: No such file or directory (os error 2) `
4343
44- * Helper methods
44+ ----------------
45+ Helper Methods
46+ ----------------
4547
46- * :rust: `.unwrap() ` - returns the value or panics
47- * :rust: `.expect("Msg") ` - like :rust: `unwrap `, with custom panic message
48- * :rust: `.unwrap_or(default) ` - fallback value on error
48+ .. code :: rust
49+
50+ let good: Result<i32, &str> = Ok(42);
51+ let bad: Result<i32, &str> = Err("Problem");
52+
53+ * :rust: `.unwrap() ` - returns the value or panics
54+
55+ .. code :: rust
56+
57+ println!("Good: {}", good.unwrap());
58+ println!("Bad: {}", bad.unwrap());
59+
60+ .. code :: output
61+
62+ Good: 42
63+ thread 'main' panicked at src\main.rs:5:27:
64+ called `Result::unwrap()` on an `Err` value: "Problem"
65+
66+ * :rust: `.expect("Msg") ` - like :rust: `unwrap `, with custom panic message
67+
68+ .. code :: rust
69+
70+ println!("Good: {}", good.expect("Expected"));
71+ println!("Bad: {}", bad.expect("Expected"));
72+
73+ .. code :: output
74+
75+ Good: 42
76+ thread 'main' panicked at src\main.rs:5:27:
77+ Expected: "Problem"
78+
79+ * :rust: `.unwrap_or(default) ` - fallback value on error
80+
81+ .. code :: rust
82+
83+ println!("Good: {}", good.unwrap_or(-1));
84+ println!("Bad: {}", bad.unwrap_or(-1));
85+
86+ .. code :: output
87+
88+ Good: 42
89+ Bad: -1
4990
5091------------------------
5192Results vs. Exceptions
Original file line number Diff line number Diff line change @@ -19,7 +19,6 @@ Automatic Error Type Conversion
1919 :font-size: tiny
2020
2121 enum Reason { TooYoung, TooOld, }
22-
2322 impl From<Reason> for String {
2423 fn from(reason: Reason) -> Self {
2524 match reason {
@@ -30,7 +29,6 @@ Automatic Error Type Conversion
3029 }
3130 }
3231 }
33-
3432 // Error type is 'Reason'
3533 fn check_age(age: i32) -> Result<i32, Reason> {
3634 if age < 18 {
@@ -40,7 +38,6 @@ Automatic Error Type Conversion
4038 } else {
4139 Ok(age)
4240 }
43-
4441 }
4542
4643 .. container :: column
@@ -55,7 +52,6 @@ Automatic Error Type Conversion
5552 check_age(age)?;
5653 Ok(age)
5754 }
58-
5955 match register(10) {
6056 Ok(age) => println!("Good enough {age}"),
6157 Err(e) => eprintln!("Problem: {e}"),
@@ -65,11 +61,10 @@ Automatic Error Type Conversion
6561 Err(e) => eprintln!("Problem: {e}"),
6662 }
6763
68- .. container :: latex_environment scriptsize
69-
70- :error: `Problem: The user is too young. `
64+ .. code :: error
7165
72- :error: `Problem: The user is too old. `
66+ Problem: The user is too young.
67+ Problem: The user is too old.
7368
7469 .. note ::
7570
You can’t perform that action at this time.
0 commit comments