You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The previous section illustrates the error handling mechanism `panic`. The `cfg_panic` feature makes it possible to execute different code depending on the panic strategy. The current values available are `unwind` and `abort`.
4
+
5
+
6
+
Building on the prior lemonade example, we explicitly use the panic strategy to execise different lines of code.
7
+
8
+
```rust,editable,ignore,mdbook-runnable
9
+
10
+
fn drink(beverage: &str) {
11
+
// You shouldn't drink too much sugary beverages.
12
+
if beverage == "lemonade" {
13
+
if cfg!(panic="abort"){ println!("This is not your party. Run!!!!");}
14
+
else{ println!("Spit it out!!!!");}
15
+
}
16
+
else{ println!("Some refreshing {} is all I need.", beverage); }
17
+
}
18
+
19
+
fn main() {
20
+
drink("water");
21
+
drink("lemonade");
22
+
}
23
+
```
24
+
25
+
Here is another example focusing on rewriting `drink()` and explicitly use the `unwind` keyword.
26
+
27
+
```rust,editable,ignore
28
+
29
+
#[cfg(panic = "unwind")]
30
+
fn ah(){ println!("Spit it out!!!!");}
31
+
32
+
#[cfg(not(panic="unwind"))]
33
+
fn ah(){ println!("This is not your party. Run!!!!");}
34
+
35
+
fn drink(beverage: &str){
36
+
if beverage == "lemonade"{ ah();}
37
+
else{println!("Some refreshing {} is all I need.", beverage);}
38
+
}
39
+
40
+
fn main() {
41
+
drink("water");
42
+
drink("lemonade");
43
+
}
44
+
```
45
+
46
+
The panic strategy can be set from the command line by using `abort` or `unwind`.
0 commit comments