Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

documentation for cfg_panic #1500

Merged
merged 3 commits into from
Feb 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@

- [Error handling](error.md)
- [`panic`](error/panic.md)
- [`abort` & `unwind`](error/abort_unwind.md)
- [`Option` & `unwrap`](error/option_unwrap.md)
- [Unpacking options with `?`](error/option_unwrap/question_mark.md)
- [Combinators: `map`](error/option_unwrap/map.md)
Expand Down
51 changes: 51 additions & 0 deletions src/error/abort_unwind.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# `abort` and `unwind`

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`.
cchiw marked this conversation as resolved.
Show resolved Hide resolved


Building on the prior lemonade example, we explicitly use the panic strategy to execise different lines of code.

```rust,editable,ignore,mdbook-runnable
cchiw marked this conversation as resolved.
Show resolved Hide resolved

fn drink(beverage: &str) {
// You shouldn't drink too much sugary beverages.
if beverage == "lemonade" {
if cfg!(panic="abort"){ println!("This is not your party. Run!!!!");}
else{ println!("Spit it out!!!!");}
}
else{ println!("Some refreshing {} is all I need.", beverage); }
}

fn main() {
drink("water");
drink("lemonade");
}
```

Here is another example focusing on rewriting `drink()` and explicitly use the `unwind` keyword.

```rust,editable,ignore
cchiw marked this conversation as resolved.
Show resolved Hide resolved

#[cfg(panic = "unwind")]
fn ah(){ println!("Spit it out!!!!");}

#[cfg(not(panic="unwind"))]
fn ah(){ println!("This is not your party. Run!!!!");}

fn drink(beverage: &str){
if beverage == "lemonade"{ ah();}
else{println!("Some refreshing {} is all I need.", beverage);}
}

fn main() {
drink("water");
drink("lemonade");
}
```

The panic strategy can be set from the command line by using `abort` or `unwind`.

```rust,editable,ignore
cchiw marked this conversation as resolved.
Show resolved Hide resolved
rustc lemonade.rc -C panic=abort
cchiw marked this conversation as resolved.
Show resolved Hide resolved
```