1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Error handling with the `Result` type
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.
19 //! enum Result<T, E> {
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).
29 //! A simple function returning `Result` might be
30 //! defined and used like so:
34 //! enum Version { Version1, Version2 }
36 //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
37 //! if header.len() < 1 {
38 //! return Err("invalid header length");
41 //! 1 => Ok(Version1),
42 //! 2 => Ok(Version2),
43 //! _ => Err("invalid version")
47 //! let version = parse_version(&[1, 2, 3, 4]);
50 //! println!("working with version: {}", v);
53 //! println!("error parsing header: {}", e);
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.
63 //! let good_result: Result<int, int> = Ok(10);
64 //! let bad_result: Result<int, int> = Err(10);
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());
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);
74 //! // Use `and_then` to continue the computation.
75 //! let good_result: Result<bool, int> = good_result.and_then(|i| Ok(i == 11));
77 //! // Use `or_else` to handle the error.
78 //! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11));
80 //! // Consume the result and return the contents with `unwrap`.
81 //! let final_awesome_result = good_result.ok().unwrap();
84 //! # Results must be used
86 //! A common problem with using return values to indicate errors is
87 //! that it is easy to ignore the return value, thus failing to handle
88 //! the error. Result is annotated with the #[must_use] attribute,
89 //! which will cause the compiler to issue a warning when a Result
90 //! value is ignored. This makes `Result` especially useful with
91 //! functions that may encounter errors but don't otherwise return a
94 //! Consider the `write_line` method defined for I/O types
95 //! by the [`Writer`](../io/trait.Writer.html) trait:
98 //! use std::io::IoError;
101 //! fn write_line(&mut self, s: &str) -> Result<(), IoError>;
105 //! *Note: The actual definition of `Writer` uses `IoResult`, which
106 //! is just a synonymn for `Result<T, IoError>`.*
108 //! This method doesn`t produce a value, but the write may
109 //! fail. It's crucial to handle the error case, and *not* write
110 //! something like this:
113 //! use std::io::{File, Open, Write};
115 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
116 //! // If `write_line` errors, then we'll never know, because the return
117 //! // value is ignored.
118 //! file.write_line("important message");
122 //! If you *do* write that in Rust, the compiler will by give you a
123 //! warning (by default, controlled by the `unused_must_use` lint).
125 //! You might instead, if you don't want to handle the error, simply
126 //! fail, by converting to an `Option` with `ok`, then asserting
127 //! success with `expect`. This will fail if the write fails, proving
128 //! a marginally useful message indicating why:
131 //! use std::io::{File, Open, Write};
133 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
134 //! file.write_line("important message").ok().expect("failed to write message");
138 //! You might also simply assert success:
141 //! # use std::io::{File, Open, Write};
143 //! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
144 //! assert!(file.write_line("important message").is_ok());
148 //! Or propagate the error up the call stack with `try!`:
151 //! # use std::io::{File, Open, Write, IoError};
152 //! fn write_message() -> Result<(), IoError> {
153 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
154 //! try!(file.write_line("important message"));
160 //! # The `try!` macro
162 //! When writing code that calls many functions that return the
163 //! `Result` type, the error handling can be tedious. The `try!`
164 //! macro hides some of the boilerplate of propagating errors up the
167 //! It replaces this:
170 //! use std::io::{File, Open, Write, IoError};
172 //! struct Info { name: ~str, age: int, rating: int }
174 //! fn write_info(info: &Info) -> Result<(), IoError> {
175 //! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
176 //! // Early return on error
177 //! match file.write_line(format!("name: {}", info.name)) {
179 //! Err(e) => return Err(e)
181 //! match file.write_line(format!("age: {}", info.age)) {
183 //! Err(e) => return Err(e)
185 //! return file.write_line(format!("rating: {}", info.rating));
192 //! use std::io::{File, Open, Write, IoError};
194 //! struct Info { name: ~str, age: int, rating: int }
196 //! fn write_info(info: &Info) -> Result<(), IoError> {
197 //! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
198 //! // Early return on error
199 //! try!(file.write_line(format!("name: {}", info.name)));
200 //! try!(file.write_line(format!("age: {}", info.age)));
201 //! try!(file.write_line(format!("rating: {}", info.rating)));
206 //! *It's much nicer!*
208 //! Wrapping an expression in `try!` will result in the unwrapped
209 //! success (`Ok`) value, unless the result is `Err`, in which case
210 //! `Err` is returned early from the enclosing function. Its simple definition
214 //! # #![feature(macro_rules)]
215 //! macro_rules! try(
216 //! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
221 //! `try!` is imported by the prelude, and is available everywhere.
223 //! # `Result` and `Option`
225 //! The `Result` and [`Option`](../option/index.html) types are
226 //! similar and complementary: they are often employed to indicate a
227 //! lack of a return value; and they are trivially converted between
228 //! each other, so `Result`s are often handled by first converting to
229 //! `Option` with the [`ok`](enum.Result.html#method.ok) and
230 //! [`err`](enum.Result.html#method.ok) methods.
232 //! Whereas `Option` only indicates the lack of a value, `Result` is
233 //! specifically for error reporting, and carries with it an error
234 //! value. Sometimes `Option` is used for indicating errors, but this
235 //! is only for simple cases and is generally discouraged. Even when
236 //! there is no useful error value to return, prefer `Result<T, ()>`.
238 //! Converting to an `Option` with `ok()` to handle an error:
241 //! use std::io::Timer;
242 //! let mut t = Timer::new().ok().expect("failed to create timer!");
245 //! # `Result` vs. `fail!`
247 //! `Result` is for recoverable errors; `fail!` is for unrecoverable
248 //! errors. Callers should always be able to avoid failure if they
249 //! take the proper precautions, for example, calling `is_some()`
250 //! on an `Option` type before calling `unwrap`.
252 //! The suitability of `fail!` as an error handling mechanism is
253 //! limited by Rust's lack of any way to "catch" and resume execution
254 //! from a thrown exception. Therefore using failure for error
255 //! handling requires encapsulating fallable code in a task. Calling
256 //! the `fail!` macro, or invoking `fail!` indirectly should be
257 //! avoided as an error reporting strategy. Failure is only for
258 //! unrecovereable errors and a failing task is typically the sign of
261 //! A module that instead returns `Results` is alerting the caller
262 //! that failure is possible, and providing precise control over how
265 //! Furthermore, failure may not be recoverable at all, depending on
266 //! the context. The caller of `fail!` should assume that execution
267 //! will not resume after failure, that failure is catastrophic.
272 use iter::{Iterator, FromIterator};
273 use option::{None, Option, Some};
275 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
277 /// See the [`std::result`](index.html) module documentation for details.
278 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd, Show, Hash)]
280 pub enum Result<T, E> {
281 /// Contains the success value
284 /// Contains the error value
288 /////////////////////////////////////////////////////////////////////////////
289 // Type implementation
290 /////////////////////////////////////////////////////////////////////////////
292 impl<T, E> Result<T, E> {
293 /////////////////////////////////////////////////////////////////////////
294 // Querying the contained values
295 /////////////////////////////////////////////////////////////////////////
297 /// Returns true if the result is `Ok`
302 /// use std::io::{File, Open, Write};
304 /// # fn do_not_run_example() { // creates a file
305 /// let mut file = File::open_mode(&Path::new("secret.txt"), Open, Write);
306 /// assert!(file.write_line("it's cold in here").is_ok());
310 pub fn is_ok(&self) -> bool {
317 /// Returns true if the result is `Err`
322 /// use std::io::{File, Open, Read};
324 /// // When opening with `Read` access, if the file does not exist
325 /// // then `open_mode` returns an error.
326 /// let bogus = File::open_mode(&Path::new("not_a_file.txt"), Open, Read);
327 /// assert!(bogus.is_err());
330 pub fn is_err(&self) -> bool {
335 /////////////////////////////////////////////////////////////////////////
336 // Adapter for each variant
337 /////////////////////////////////////////////////////////////////////////
339 /// Convert from `Result<T, E>` to `Option<T>`
341 /// Converts `self` into an `Option<T>`, consuming `self`,
342 /// and discarding the error, if any.
344 /// To convert to an `Option` without discarding the error value,
345 /// use `as_ref` to first convert the `Result<T, E>` into a
346 /// `Result<&T, &E>`.
350 /// ~~~{.should_fail}
351 /// use std::io::{File, IoResult};
353 /// let bdays: IoResult<File> = File::open(&Path::new("important_birthdays.txt"));
354 /// let bdays: File = bdays.ok().expect("unable to open birthday file");
357 pub fn ok(self) -> Option<T> {
364 /// Convert from `Result<T, E>` to `Option<E>`
366 /// Converts `self` into an `Option<T>`, consuming `self`,
367 /// and discarding the value, if any.
369 pub fn err(self) -> Option<E> {
376 /////////////////////////////////////////////////////////////////////////
377 // Adapter for working with references
378 /////////////////////////////////////////////////////////////////////////
380 /// Convert from `Result<T, E>` to `Result<&T, &E>`
382 /// Produces a new `Result`, containing a reference
383 /// into the original, leaving the original in place.
385 pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
388 Err(ref x) => Err(x),
392 /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
394 pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
396 Ok(ref mut x) => Ok(x),
397 Err(ref mut x) => Err(x),
401 /////////////////////////////////////////////////////////////////////////
402 // Transforming contained values
403 /////////////////////////////////////////////////////////////////////////
405 /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
406 /// contained `Ok` value, leaving an `Err` value untouched.
408 /// This function can be used to compose the results of two functions.
412 /// Sum the lines of a buffer by mapping strings to numbers,
413 /// ignoring I/O and parse errors:
416 /// use std::io::{BufReader, IoResult};
418 /// let buffer = "1\n2\n3\n4\n";
419 /// let mut reader = BufReader::new(buffer.as_bytes());
423 /// while !reader.eof() {
424 /// let line: IoResult<~str> = reader.read_line();
425 /// // Convert the string line to a number using `map` and `from_str`
426 /// let val: IoResult<int> = line.map(|line| {
427 /// from_str::<int>(line).unwrap_or(0)
429 /// // Add the value if there were no errors, otherwise add 0
430 /// sum += val.ok().unwrap_or(0);
434 pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
441 /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
442 /// contained `Err` value, leaving an `Ok` value untouched.
444 /// This function can be used to pass through a successful result while handling
447 pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
454 ////////////////////////////////////////////////////////////////////////
455 // Boolean operations on the values, eager and lazy
456 /////////////////////////////////////////////////////////////////////////
458 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
460 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
467 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
469 /// This function can be used for control flow based on result values
471 pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
478 /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
480 pub fn or(self, res: Result<T, E>) -> Result<T, E> {
487 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
489 /// This function can be used for control flow based on result values
491 pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
498 /// Unwraps a result, yielding the content of an `Ok`.
499 /// Else it returns `optb`.
501 pub fn unwrap_or(self, optb: T) -> T {
508 /// Unwraps a result, yielding the content of an `Ok`.
509 /// If the value is an `Err` then it calls `op` with its value.
511 pub fn unwrap_or_handle(self, op: |E| -> T) -> T {
519 impl<T, E: Show> Result<T, E> {
520 /// Unwraps a result, yielding the content of an `Ok`.
522 /// Fails if the value is an `Err`.
524 pub fn unwrap(self) -> T {
528 fail!("called `Result::unwrap()` on an `Err` value: {}", e)
533 impl<T: Show, E> Result<T, E> {
534 /// Unwraps a result, yielding the content of an `Err`.
536 /// Fails if the value is an `Ok`.
538 pub fn unwrap_err(self) -> E {
541 fail!("called `Result::unwrap_err()` on an `Ok` value: {}", t),
547 /////////////////////////////////////////////////////////////////////////////
549 /////////////////////////////////////////////////////////////////////////////
551 /// Takes each element in the `Iterator`: if it is an `Err`, no further
552 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
553 /// vector containing the values of each `Result` is returned.
555 /// Here is an example which increments every integer in a vector,
556 /// checking for overflow:
558 /// fn inc_conditionally(x: uint) -> Result<uint, &'static str> {
559 /// if x == uint::MAX { return Err("overflow"); }
560 /// else { return Ok(x+1u); }
562 /// let v = [1u, 2, 3];
563 /// let res = collect(v.iter().map(|&x| inc_conditionally(x)));
564 /// assert!(res == Ok(~[2u, 3, 4]));
566 pub fn collect<T, E, Iter: Iterator<Result<T, E>>, V: FromIterator<T>>(iter: Iter) -> Result<V, E> {
567 // FIXME(#11084): This should be twice as fast once this bug is closed.
568 let mut iter = iter.scan(None, |state, x| {
578 let v: V = FromIterator::from_iter(iter.by_ref());
581 Some(err) => Err(err),
586 /// Perform a fold operation over the result values from an iterator.
588 /// If an `Err` is encountered, it is immediately returned.
589 /// Otherwise, the folded value is returned.
594 Iter: Iterator<Result<T, E>>>(
601 Ok(v) => init = f(init, v),
602 Err(u) => return Err(u)
608 /// Perform a trivial fold operation over the result values
609 /// from an iterator.
611 /// If an `Err` is encountered, it is immediately returned.
612 /// Otherwise, a simple `Ok(())` is returned.
614 pub fn fold_<T,E,Iter:Iterator<Result<T,E>>>(iterator: Iter) -> Result<(),E> {
615 fold(iterator, (), |_, _| ())
618 /////////////////////////////////////////////////////////////////////////////
620 /////////////////////////////////////////////////////////////////////////////
629 pub fn op1() -> Result<int, ~str> { Ok(666) }
630 pub fn op2() -> Result<int, ~str> { Err(~"sadface") }
634 assert_eq!(op1().and(Ok(667)).unwrap(), 667);
635 assert_eq!(op1().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"bad");
637 assert_eq!(op2().and(Ok(667)).unwrap_err(), ~"sadface");
638 assert_eq!(op2().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"sadface");
642 pub fn test_and_then() {
643 assert_eq!(op1().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap(), 667);
644 assert_eq!(op1().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"bad");
646 assert_eq!(op2().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap_err(), ~"sadface");
647 assert_eq!(op2().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"sadface");
652 assert_eq!(op1().or(Ok(667)).unwrap(), 666);
653 assert_eq!(op1().or(Err(~"bad")).unwrap(), 666);
655 assert_eq!(op2().or(Ok(667)).unwrap(), 667);
656 assert_eq!(op2().or(Err(~"bad")).unwrap_err(), ~"bad");
660 pub fn test_or_else() {
661 assert_eq!(op1().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 666);
662 assert_eq!(op1().or_else(|e| Err::<int, ~str>(e + "!")).unwrap(), 666);
664 assert_eq!(op2().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 667);
665 assert_eq!(op2().or_else(|e| Err::<int, ~str>(e + "!")).unwrap_err(), ~"sadface!");
669 pub fn test_impl_map() {
670 assert_eq!(Ok::<~str, ~str>(~"a").map(|x| x + "b"), Ok(~"ab"));
671 assert_eq!(Err::<~str, ~str>(~"a").map(|x| x + "b"), Err(~"a"));
675 pub fn test_impl_map_err() {
676 assert_eq!(Ok::<~str, ~str>(~"a").map_err(|x| x + "b"), Ok(~"a"));
677 assert_eq!(Err::<~str, ~str>(~"a").map_err(|x| x + "b"), Err(~"ab"));
682 let v: Result<~[int], ()> = collect(range(0, 0).map(|_| Ok::<int, ()>(0)));
683 assert_eq!(v, Ok(~[]));
685 let v: Result<~[int], ()> = collect(range(0, 3).map(|x| Ok::<int, ()>(x)));
686 assert_eq!(v, Ok(~[0, 1, 2]));
688 let v: Result<~[int], int> = collect(range(0, 3)
689 .map(|x| if x > 1 { Err(x) } else { Ok(x) }));
690 assert_eq!(v, Err(2));
692 // test that it does not take more elements than it needs
693 let functions = [|| Ok(()), || Err(1), || fail!()];
695 let v: Result<~[()], int> = collect(functions.iter().map(|f| (*f)()));
696 assert_eq!(v, Err(1));
701 assert_eq!(fold_(range(0, 0)
702 .map(|_| Ok::<(), ()>(()))),
704 assert_eq!(fold(range(0, 3)
705 .map(|x| Ok::<int, ()>(x)),
708 assert_eq!(fold_(range(0, 3)
709 .map(|x| if x > 1 { Err(x) } else { Ok(()) })),
712 // test that it does not take more elements than it needs
713 let functions = [|| Ok(()), || Err(1), || fail!()];
715 assert_eq!(fold_(functions.iter()
721 pub fn test_to_str() {
722 let ok: Result<int, ~str> = Ok(100);
723 let err: Result<int, ~str> = Err(~"Err");
725 assert_eq!(ok.to_str(), ~"Ok(100)");
726 assert_eq!(err.to_str(), ~"Err(Err)");
730 pub fn test_fmt_default() {
731 let ok: Result<int, ~str> = Ok(100);
732 let err: Result<int, ~str> = Err(~"Err");
734 assert_eq!(format!("{}", ok), ~"Ok(100)");
735 assert_eq!(format!("{}", err), ~"Err(Err)");
739 pub fn test_unwrap_or() {
740 let ok: Result<int, ~str> = Ok(100);
741 let ok_err: Result<int, ~str> = Err(~"Err");
743 assert_eq!(ok.unwrap_or(50), 100);
744 assert_eq!(ok_err.unwrap_or(50), 50);
748 pub fn test_unwrap_or_else() {
749 fn handler(msg: ~str) -> int {
750 if msg == ~"I got this." {
757 let ok: Result<int, ~str> = Ok(100);
758 let ok_err: Result<int, ~str> = Err(~"I got this.");
760 assert_eq!(ok.unwrap_or_handle(handler), 100);
761 assert_eq!(ok_err.unwrap_or_handle(handler), 50);
766 pub fn test_unwrap_or_else_failure() {
767 fn handler(msg: ~str) -> int {
768 if msg == ~"I got this." {
775 let bad_err: Result<int, ~str> = Err(~"Unrecoverable mess.");
776 let _ : int = bad_err.unwrap_or_handle(handler);