Skip to content

Commit f31ea22

Browse files
committed
Mention try macro in error chapter
Fixes #22342
1 parent dccdde4 commit f31ea22

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

src/doc/trpl/error-handling.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,78 @@ let input = io::stdin().read_line()
223223
.ok()
224224
.expect("Failed to read line");
225225
```
226+
226227
`ok()` converts the `IoResult` into an `Option`, and `expect()` does the same
227228
thing as `unwrap()`, but takes a message. This message is passed along to the
228229
underlying `panic!`, providing a better error message if the code errors.
230+
231+
# Using `try!`
232+
233+
When writing code that calls many functions that return the `Result` type, the
234+
error handling can be tedious. The `try!` macro hides some of the boilerplate
235+
of propagating errors up the call stack.
236+
237+
It replaces this:
238+
239+
```rust
240+
use std::fs::File;
241+
use std::io;
242+
use std::io::prelude::*;
243+
244+
struct Info {
245+
name: String,
246+
age: i32,
247+
rating: i32,
248+
}
249+
250+
fn write_info(info: &Info) -> io::Result<()> {
251+
let mut file = File::open("my_best_friends.txt").unwrap();
252+
253+
if let Err(e) = writeln!(&mut file, "name: {}", info.name) {
254+
return Err(e)
255+
}
256+
if let Err(e) = writeln!(&mut file, "age: {}", info.age) {
257+
return Err(e)
258+
}
259+
if let Err(e) = writeln!(&mut file, "rating: {}", info.rating) {
260+
return Err(e)
261+
}
262+
263+
return Ok(());
264+
}
265+
```
266+
267+
With this:
268+
269+
```rust
270+
use std::fs::File;
271+
use std::io;
272+
use std::io::prelude::*;
273+
274+
struct Info {
275+
name: String,
276+
age: i32,
277+
rating: i32,
278+
}
279+
280+
fn write_info(info: &Info) -> io::Result<()> {
281+
let mut file = try!(File::open("my_best_friends.txt"));
282+
283+
try!(writeln!(&mut file, "name: {}", info.name));
284+
try!(writeln!(&mut file, "age: {}", info.age));
285+
try!(writeln!(&mut file, "rating: {}", info.rating));
286+
287+
return Ok(());
288+
}
289+
```
290+
291+
Wrapping an expression in `try!` will result in the unwrapped success (`Ok`)
292+
value, unless the result is `Err`, in which case `Err` is returned early from
293+
the enclosing function.
294+
295+
It's worth noting that you can only use `try!` from a function that returns a
296+
`Result`, which means that you cannot use `try!` inside of `main()`, because
297+
`main()` doesn't return anything.
298+
299+
`try!` makes use of [`FromError`](../std/error/#the-fromerror-trait) to determine
300+
what to return in the error case.

0 commit comments

Comments
 (0)