Skip to content

Commit 8186f0d

Browse files
authored
Merge pull request #1500 from cchiw/master
documentation for cfg_panic
2 parents 18c0055 + 0b3ccde commit 8186f0d

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/SUMMARY.md

+1
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,7 @@
155155

156156
- [Error handling](error.md)
157157
- [`panic`](error/panic.md)
158+
- [`abort` & `unwind`](error/abort_unwind.md)
158159
- [`Option` & `unwrap`](error/option_unwrap.md)
159160
- [Unpacking options with `?`](error/option_unwrap/question_mark.md)
160161
- [Combinators: `map`](error/option_unwrap/map.md)

src/error/abort_unwind.md

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# `abort` and `unwind`
2+
3+
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`.
47+
48+
```rust,editable,ignore
49+
rustc lemonade.rc -C panic=abort
50+
```
51+

0 commit comments

Comments
 (0)