8
8
// option. This file may not be copied, modified, or distributed
9
9
// except according to those terms.
10
10
11
- //! Signaling success or failure states (`Result` type)
11
+ //! Error handling with the `Result` type
12
+ //!
13
+ //! `Result<T>` is the type used for returning and propagating
14
+ //! errors. It is an enum with the variants, `Ok(T)`, representing
15
+ //! success and containing a value, and `Err(E)`, representing error
16
+ //! and containing an error value.
17
+ //!
18
+ //! ~~~
19
+ //! enum Result<T, E> {
20
+ //! Ok(T),
21
+ //! Err(E)
22
+ //! }
23
+ //! ~~~
24
+ //!
25
+ //! Functions return `Result` whenever errors are expected and
26
+ //! recoverable. In the `std` crate `Result` is most prominently used
27
+ //! for [I/O](../io/index.html).
28
+ //!
29
+ //! A simple function returning `Result` might be
30
+ //! defined and used like so:
31
+ //!
32
+ //! ~~~
33
+ //! #[deriving(Show)]
34
+ //! enum Version { Version1, Version2 }
35
+ //!
36
+ //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
37
+ //! if header.len() < 1 {
38
+ //! return Err("invalid header length");;
39
+ //! }
40
+ //! match header[0] {
41
+ //! 1 => Ok(Version1),
42
+ //! 2 => Ok(Version2),
43
+ //! _ => Err("invalid version")
44
+ //! }
45
+ //! }
46
+ //!
47
+ //! let version = parse_version(&[1, 2, 3, 4]);
48
+ //! match version {
49
+ //! Ok(v) => {
50
+ //! println!("working with version: {}", v);
51
+ //! }
52
+ //! Err(e) => {
53
+ //! println!("error parsing header: {}", e);
54
+ //! }
55
+ //! }
56
+ //! ~~~
57
+ //!
58
+ //! Pattern matching on `Result`s is clear and straightforward for
59
+ //! simple cases, but `Result` comes with some convenience methods
60
+ //! that make working it more succinct.
61
+ //!
62
+ //! ~~~
63
+ //! let good_result: Result<int, int> = Ok(10);
64
+ //! let bad_result: Result<int, int> = Err(10);
65
+ //!
66
+ //! // The `is_ok` and `is_err` methods do what they say.
67
+ //! assert!(good_result.is_ok() && !good_result.is_err());
68
+ //! assert!(bad_result.is_err() && !bad_result.is_ok());
69
+ //!
70
+ //! // `map` consumes the `Result` and produces another.
71
+ //! let good_result: Result<int, int> = good_result.map(|i| i + 1);
72
+ //! let bad_result: Result<int, int> = bad_result.map(|i| i - 1);
73
+ //!
74
+ //! // Use `and_then` to continue the computation.
75
+ //! let good_result: Result<bool, int> = good_result.and_then(|i| Ok(i == 11));
76
+ //!
77
+ //! // Use `or_else` to handle the error.
78
+ //! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11));
79
+ //!
80
+ //! // Convert to an `Option` to call e.g. `unwrap`.
81
+ //! let final_awesome_result = good_result.ok().unwrap();
82
+ //! ~~~
83
+ //!
84
+ //! # Results must be used
85
+ //!
86
+ //! A common problem with using return values to indicate errors
87
+ //! is that it is easy to ignore the return value, thus failing
88
+ //! to handle the error. By possessing the `#[must_use]` attribute,
89
+ //! the compiler will warn when a `Result` type is ignored. This
90
+ //! makes `Result` especially useful with functions that may
91
+ //! encounter errors but don't otherwise return a useful value.
92
+ //!
93
+ //! Consider the `write_line` method defined for I/O types
94
+ //! by the [`Writer`](../io/trait.Writer.html) trait:
95
+ //!
96
+ //! ~~~
97
+ //! use std::io::IoError;
98
+ //!
99
+ //! trait Writer {
100
+ //! fn write_line(&mut self, s: &str) -> Result<(), IoError>;
101
+ //! }
102
+ //! ~~~
103
+ //!
104
+ //! *Note: The actual definition of `Writer` uses `IoResult`, which
105
+ //! is just a synonymn for `Result<T, IoError>`.*
106
+ //!
107
+ //! This method doesn`t produce a value, but the write may
108
+ //! fail. It's crucial to handle the error case, and *not* write
109
+ //! something like this:
110
+ //!
111
+ //! ~~~ignore
112
+ //! use std::io::{File, Open, Write};
113
+ //!
114
+ //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
115
+ //! // If `write_line` errors, then we'll never know, because the return
116
+ //! // value is ignored.
117
+ //! file.write_line("important message");
118
+ //! drop(file);
119
+ //! ~~~
120
+ //!
121
+ //! If you *do* write that in Rust, the compiler will by give you a
122
+ //! warning (by default, controlled by the `unused_must_use` lint).
123
+ //!
124
+ //! You might instead, if you don't want to handle the error, simply
125
+ //! fail, by converting to an `Option` with `ok`, then asserting
126
+ //! success with `expect`. This will fail if the write fails, proving
127
+ //! a marginally useful message indicating why:
128
+ //!
129
+ //! ~~~
130
+ //! # // not running this test because it creates a file
131
+ //! # fn do_not_run_test() {
132
+ //! use std::io::{File, Open, Write};
133
+ //!
134
+ //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
135
+ //! file.write_line("important message").ok().expect("failed to write message");
136
+ //! drop(file);
137
+ //! # }
138
+ //! ~~~
139
+ //!
140
+ //! You might also simply assert success:
141
+ //!
142
+ //! ~~~
143
+ //! # // not running this test because it creates a file
144
+ //! # fn do_not_run_test() {
145
+ //! # use std::io::{File, Open, Write};
146
+ //!
147
+ //! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
148
+ //! assert!(file.write_line("important message").is_ok());
149
+ //! # drop(file);
150
+ //! # }
151
+ //! ~~~
152
+ //!
153
+ //! Or propagate the error up the call stack with `try!`:
154
+ //!
155
+ //! ~~~
156
+ //! # use std::io::{File, Open, Write, IoError};
157
+ //! fn write_message() -> Result<(), IoError> {
158
+ //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
159
+ //! try!(file.write_line("important message"));
160
+ //! drop(file);
161
+ //! return Ok(());
162
+ //! }
163
+ //! ~~~
164
+ //!
165
+ //! # The `try!` macro
166
+ //!
167
+ //! When writing code that calls many functions that return the
168
+ //! `Result` type, the error handling can be tedious. The `try!`
169
+ //! macro hides some of the boilerplate of propagating errors up the
170
+ //! call stack.
171
+ //!
172
+ //! It replaces this:
173
+ //!
174
+ //! ~~~
175
+ //! use std::io::{File, Open, Write, IoError};
176
+ //!
177
+ //! struct Info { name: ~str, age: int, rating: int }
178
+ //!
179
+ //! fn write_info(info: &Info) -> Result<(), IoError> {
180
+ //! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
181
+ //! // Early return on error
182
+ //! match file.write_line(format!("name: {}", info.name)) {
183
+ //! Ok(_) => (),
184
+ //! Err(e) => return Err(e)
185
+ //! }
186
+ //! match file.write_line(format!("age: {}", info.age)) {
187
+ //! Ok(_) => (),
188
+ //! Err(e) => return Err(e)
189
+ //! }
190
+ //! return file.write_line(format!("rating: {}", info.rating));
191
+ //! }
192
+ //! ~~~
193
+ //!
194
+ //! With this:
195
+ //!
196
+ //! ~~~
197
+ //! use std::io::{File, Open, Write, IoError};
198
+ //!
199
+ //! struct Info { name: ~str, age: int, rating: int }
200
+ //!
201
+ //! fn write_info(info: &Info) -> Result<(), IoError> {
202
+ //! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
203
+ //! // Early return on error
204
+ //! try!(file.write_line(format!("name: {}", info.name)));
205
+ //! try!(file.write_line(format!("age: {}", info.age)));
206
+ //! try!(file.write_line(format!("rating: {}", info.rating)));
207
+ //! return Ok(());
208
+ //! }
209
+ //! ~~~
210
+ //!
211
+ //! *It's much nicer!*
212
+ //!
213
+ //! Wrapping an expression in `try!` will result in the unwrapped
214
+ //! success (`Ok`) value, unless the result is `Err`, in which case
215
+ //! `Err` is returned early from the enclosing function. Its simple definition
216
+ //! makes it clear:
217
+ //!
218
+ //! ~~~ignore
219
+ //! macro_rules! try(
220
+ //! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
221
+ //! )
222
+ //! ~~~
223
+ //!
224
+ //! `try!` is imported by the prelude, and is available everywhere.
225
+ //!
226
+ //! # `Result` and `Option`
227
+ //!
228
+ //! The `Result` and [`Option`](../option/index.html) types are
229
+ //! similar and complementary: they are often employed to indicate a
230
+ //! lack of a return value; and they are trivially converted between
231
+ //! each other, so `Result`s are often handled by first converting to
232
+ //! `Option` with the [`ok`](enum.Result.html#method.ok) and
233
+ //! [`err`](enum.Result.html#method.ok) methods.
234
+ //!
235
+ //! Whereas `Option` only indicates the lack of a value, `Result` is
236
+ //! specifically for error reporting, and carries with it an error
237
+ //! value. Sometimes `Option` is used for indicating errors, but this
238
+ //! is only for simple cases and is generally discouraged. Even when
239
+ //! there is no useful error value to return, prefer `Result<T, ()>`.
240
+ //!
241
+ //! Converting to an `Option` with `ok()` to handle an error:
242
+ //!
243
+ //! ~~~
244
+ //! use std::io::Timer;
245
+ //! let mut t = Timer::new().ok().expect("failed to create timer!");
246
+ //! ~~~
247
+ //!
248
+ //! # `Result` vs. `fail!`
249
+ //!
250
+ //! `Result` is for recoverable errors; `fail!` is for unrecoverable
251
+ //! errors. Callers should always be able to avoid failure if they
252
+ //! take the proper precautions, for example, calling `is_some()`
253
+ //! on an `Option` type before calling `unwrap`.
254
+ //!
255
+ //! The suitability of `fail!` as an error handling mechanism is
256
+ //! limited by Rust's lack of any way to "catch" and resume execution
257
+ //! from a thrown exception. Therefore using failure for error
258
+ //! handling requires encapsulating fallable code in a task. Calling
259
+ //! the `fail!` macro, or invoking `fail!` indirectly should be
260
+ //! avoided as an error reporting strategy. Failure is only for
261
+ //! unrecovereable errors and a failing task is typically the sign of
262
+ //! a bug.
263
+ //!
264
+ //! A module that instead returns `Results` is alerting the caller
265
+ //! that failure is possible, and providing precise control over how
266
+ //! it is handled.
267
+ //!
268
+ //! Furthermore, failure may not be recoverable at all, depending on
269
+ //! the context. The caller of `fail!` should assume that execution
270
+ //! will not resume after failure, that failure is catastrophic.
12
271
13
272
use clone:: Clone ;
14
273
use cmp:: Eq ;
@@ -17,6 +276,8 @@ use iter::{Iterator, FromIterator};
17
276
use option:: { None , Option , Some } ;
18
277
19
278
/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
279
+ ///
280
+ /// See the [`std::result`](index.html) module documentation for details.
20
281
#[ deriving( Clone , Eq , Ord , TotalEq , TotalOrd , Show ) ]
21
282
#[ must_use]
22
283
pub enum Result < T , E > {
@@ -37,6 +298,17 @@ impl<T, E> Result<T, E> {
37
298
/////////////////////////////////////////////////////////////////////////
38
299
39
300
/// Returns true if the result is `Ok`
301
+ ///
302
+ /// # Example
303
+ ///
304
+ /// ~~~
305
+ /// use std::io::{File, Open, Write};
306
+ ///
307
+ /// # fn do_not_run_example() { // creates a file
308
+ /// let mut file = File::open_mode(&Path::new("secret.txt"), Open, Write);
309
+ /// assert!(file.write_line("it's cold in here").is_ok());
310
+ /// # }
311
+ /// ~~~
40
312
#[ inline]
41
313
pub fn is_ok ( & self ) -> bool {
42
314
match * self {
@@ -46,6 +318,17 @@ impl<T, E> Result<T, E> {
46
318
}
47
319
48
320
/// Returns true if the result is `Err`
321
+ ///
322
+ /// # Example
323
+ ///
324
+ /// ~~~
325
+ /// use std::io::{File, Open, Read};
326
+ ///
327
+ /// // When opening with `Read` access, if the file does not exist
328
+ /// // then `open_mode` returns an error.
329
+ /// let bogus = File::open_mode(&Path::new("not_a_file.txt"), Open, Read);
330
+ /// assert!(bogus.is_err());
331
+ /// ~~~
49
332
#[ inline]
50
333
pub fn is_err ( & self ) -> bool {
51
334
!self . is_ok ( )
@@ -57,6 +340,22 @@ impl<T, E> Result<T, E> {
57
340
/////////////////////////////////////////////////////////////////////////
58
341
59
342
/// Convert from `Result<T, E>` to `Option<T>`
343
+ ///
344
+ /// Converts `self` into an `Option<T>`, consuming `self`,
345
+ /// and discarding the error, if any.
346
+ ///
347
+ /// To convert to an `Option` without discarding the error value,
348
+ /// use `as_ref` to first convert the `Result<T, E>` into a
349
+ /// `Result<&T, &E>`.
350
+ ///
351
+ /// # Examples
352
+ ///
353
+ /// ~~~{.should_fail}
354
+ /// use std::io::{File, IoResult};
355
+ ///
356
+ /// let bdays: IoResult<File> = File::open(&Path::new("important_birthdays.txt"));
357
+ /// let bdays: File = bdays.ok().expect("unable to open birthday file");
358
+ /// ~~~
60
359
#[ inline]
61
360
pub fn ok ( self ) -> Option < T > {
62
361
match self {
@@ -66,6 +365,9 @@ impl<T, E> Result<T, E> {
66
365
}
67
366
68
367
/// Convert from `Result<T, E>` to `Option<E>`
368
+ ///
369
+ /// Converts `self` into an `Option<T>`, consuming `self`,
370
+ /// and discarding the value, if any.
69
371
#[ inline]
70
372
pub fn err ( self ) -> Option < E > {
71
373
match self {
@@ -79,6 +381,9 @@ impl<T, E> Result<T, E> {
79
381
/////////////////////////////////////////////////////////////////////////
80
382
81
383
/// Convert from `Result<T, E>` to `Result<&T, &E>`
384
+ ///
385
+ /// Produces a new `Result`, containing a reference
386
+ /// into the original, leaving the original in place.
82
387
#[ inline]
83
388
pub fn as_ref < ' r > ( & ' r self ) -> Result < & ' r T , & ' r E > {
84
389
match * self {
@@ -105,11 +410,29 @@ impl<T, E> Result<T, E> {
105
410
///
106
411
/// This function can be used to compose the results of two functions.
107
412
///
108
- /// Example:
413
+ /// # Examples
414
+ ///
415
+ /// Sum the lines of a buffer by mapping strings to numbers,
416
+ /// ignoring I/O and parse errors:
417
+ ///
418
+ /// ~~~
419
+ /// use std::io::{BufReader, IoResult};
420
+ ///
421
+ /// let buffer = "1\n2\n3\n4\n";
422
+ /// let mut reader = BufReader::new(buffer.as_bytes());
423
+ ///
424
+ /// let mut sum = 0;
109
425
///
110
- /// let res = read_file(file).map(|buf| {
111
- /// parse_bytes(buf)
112
- /// })
426
+ /// while !reader.eof() {
427
+ /// let line: IoResult<~str> = reader.read_line();
428
+ /// // Convert the string line to a number using `map` and `from_str`
429
+ /// let val: IoResult<int> = line.map(|line| {
430
+ /// from_str::<int>(line).unwrap_or(0)
431
+ /// });
432
+ /// // Add the value if there were no errors, otherwise add 0
433
+ /// sum += val.ok().unwrap_or(0);
434
+ /// }
435
+ /// ~~~
113
436
#[ inline]
114
437
pub fn map < U > ( self , op: |T | -> U ) -> Result < U , E > {
115
438
match self {
0 commit comments