@@ -223,6 +223,78 @@ let input = io::stdin().read_line()
223
223
.ok()
224
224
.expect("Failed to read line");
225
225
```
226
+
226
227
` ok() ` converts the ` IoResult ` into an ` Option ` , and ` expect() ` does the same
227
228
thing as ` unwrap() ` , but takes a message. This message is passed along to the
228
229
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