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 synonym 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`](../../core/result/enum.Result.html#method.ok) and
230 //! [`err`](../../core/result/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 //! unrecoverable 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.
271 pub use core::result::{Result, Ok, Err, collect, fold, fold_};
273 // FIXME: These traits should not exist. Once std::fmt is moved to libcore,
274 // these can once again become inherent methods on Result.
276 /// Temporary trait for unwrapping a result
277 pub trait ResultUnwrap<T, E> {
278 /// Unwraps a result, yielding the content of an `Ok`.
280 /// Fails if the value is an `Err`.
281 fn unwrap(self) -> T;
284 /// Temporary trait for unwrapping the error of a result
285 pub trait ResultUnwrapErr<T, E> {
286 /// Unwraps a result, yielding the content of an `Err`.
288 /// Fails if the value is an `Ok`.
289 fn unwrap_err(self) -> E;
292 impl<T, E: Show> ResultUnwrap<T, E> for Result<T, E> {
294 fn unwrap(self) -> T {
298 fail!("called `Result::unwrap()` on an `Err` value: {}", e)
303 impl<T: Show, E> ResultUnwrapErr<T, E> for Result<T, E> {
305 fn unwrap_err(self) -> E {
308 fail!("called `Result::unwrap_err()` on an `Ok` value: {}", t),