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

added documentation for cfg_panic #3038

Closed
wants to merge 2 commits into from
Closed
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
45 changes: 45 additions & 0 deletions src/ch09-01-unrecoverable-errors-with-panic.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,51 @@ request an element beyond the range of the vector indexes. When your code
panics in the future, you’ll need to figure out what action the code is taking
with what values to cause the panic and what the code should do instead.

### Different panic strategies
The `cfg_panic` feature makes it possible to exercise different lines of code depending on the panic strategy.
The possible value is either `unwind` or `abort`.
The following is a playful example on choosing the right beverage.

```toml
#![feature(cfg_panic)]

#[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");
}
```

Here is the same example rewritten.
```toml
#![feature(cfg_panic)]

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");
}
```

### Summary
We’ll come back to `panic!` and when we should and should not use `panic!` to
handle error conditions in the [“To `panic!` or Not to
`panic!`”][to-panic-or-not-to-panic]<!-- ignore --> section later in this
Expand Down