Skip to content

Commit

Permalink
Demonstrate a better expect message. Fixes #2918.
Browse files Browse the repository at this point in the history
  • Loading branch information
carols10cents committed May 31, 2022
1 parent a87db22 commit 1b99347
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::fs::File;

fn main() {
let f = File::open("hello.txt").expect("Failed to open hello.txt");
let greeting_file = File::open("hello.txt")
.expect("hello.txt should be included in this project");
}
20 changes: 13 additions & 7 deletions src/ch09-02-recoverable-errors-with-result.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,16 +209,22 @@ the `panic!` macro. The error message used by `expect` in its call to `panic!`
will be the parameter that we pass to `expect`, rather than the default
`panic!` message that `unwrap` uses. Here’s what it looks like:

<!-- manual-regeneration
cd listings/ch09-error-handling/no-listing-05-expect
cargo run
copy and paste relevant text
-->

```text
thread 'main' panicked at 'Failed to open hello.txt: Error { repr: Os { code:
2, message: "No such file or directory" } }', src/libcore/result.rs:906:4
thread 'main' panicked at 'hello.txt should be included in this project: Error
{ repr: Os { code: 2, message: "No such file or directory" } }',
src/libcore/result.rs:906:4
```

Because this error message starts with the text we specified, `Failed to open
hello.txt`, it will be easier to find where in the code this error message is
coming from. If we use `unwrap` in multiple places, it can take more time to
figure out exactly which `unwrap` is causing the panic because all `unwrap`
calls that panic print the same message.
In production-quality code, most Rustaceans choose `expect` rather than
`unwrap` and give more context about why the operation is expected to always
succeed. That way, if your assumptions are ever proven wrong, you have more
information to use in debugging.

### Propagating Errors

Expand Down

0 comments on commit 1b99347

Please sign in to comment.