PageRenderTime 68ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/src/doc/trpl/error-handling.md

http://github.com/eholk/rust
Markdown | 300 lines | 229 code | 71 blank | 0 comment | 0 complexity | 09b0d4595f9690ed289e9e2f287306fd MD5 | raw file
Possible License(s): AGPL-1.0, BSD-2-Clause, 0BSD, Apache-2.0, MIT, LGPL-2.0
  1. % Error Handling
  2. > The best-laid plans of mice and men
  3. > Often go awry
  4. >
  5. > "Tae a Moose", Robert Burns
  6. Sometimes, things just go wrong. It's important to have a plan for when the
  7. inevitable happens. Rust has rich support for handling errors that may (let's
  8. be honest: will) occur in your programs.
  9. There are two main kinds of errors that can occur in your programs: failures,
  10. and panics. Let's talk about the difference between the two, and then discuss
  11. how to handle each. Then, we'll discuss upgrading failures to panics.
  12. # Failure vs. Panic
  13. Rust uses two terms to differentiate between two forms of error: failure, and
  14. panic. A *failure* is an error that can be recovered from in some way. A
  15. *panic* is an error that cannot be recovered from.
  16. What do we mean by "recover"? Well, in most cases, the possibility of an error
  17. is expected. For example, consider the `from_str` function:
  18. ```{rust,ignore}
  19. from_str("5");
  20. ```
  21. This function takes a string argument and converts it into another type. But
  22. because it's a string, you can't be sure that the conversion actually works.
  23. For example, what should this convert to?
  24. ```{rust,ignore}
  25. from_str("hello5world");
  26. ```
  27. This won't work. So we know that this function will only work properly for some
  28. inputs. It's expected behavior. We call this kind of error a *failure*.
  29. On the other hand, sometimes, there are errors that are unexpected, or which
  30. we cannot recover from. A classic example is an `assert!`:
  31. ```{rust,ignore}
  32. assert!(x == 5);
  33. ```
  34. We use `assert!` to declare that something is true. If it's not true, something
  35. is very wrong. Wrong enough that we can't continue with things in the current
  36. state. Another example is using the `unreachable!()` macro:
  37. ```{rust,ignore}
  38. enum Event {
  39. NewRelease,
  40. }
  41. fn probability(_: &Event) -> f64 {
  42. // real implementation would be more complex, of course
  43. 0.95
  44. }
  45. fn descriptive_probability(event: Event) -> &'static str {
  46. match probability(&event) {
  47. 1.00 => "certain",
  48. 0.00 => "impossible",
  49. 0.00 ... 0.25 => "very unlikely",
  50. 0.25 ... 0.50 => "unlikely",
  51. 0.50 ... 0.75 => "likely",
  52. 0.75 ... 1.00 => "very likely",
  53. }
  54. }
  55. fn main() {
  56. std::io::println(descriptive_probability(NewRelease));
  57. }
  58. ```
  59. This will give us an error:
  60. ```text
  61. error: non-exhaustive patterns: `_` not covered [E0004]
  62. ```
  63. While we know that we've covered all possible cases, Rust can't tell. It
  64. doesn't know that probability is between 0.0 and 1.0. So we add another case:
  65. ```rust
  66. use Event::NewRelease;
  67. enum Event {
  68. NewRelease,
  69. }
  70. fn probability(_: &Event) -> f64 {
  71. // real implementation would be more complex, of course
  72. 0.95
  73. }
  74. fn descriptive_probability(event: Event) -> &'static str {
  75. match probability(&event) {
  76. 1.00 => "certain",
  77. 0.00 => "impossible",
  78. 0.00 ... 0.25 => "very unlikely",
  79. 0.25 ... 0.50 => "unlikely",
  80. 0.50 ... 0.75 => "likely",
  81. 0.75 ... 1.00 => "very likely",
  82. _ => unreachable!()
  83. }
  84. }
  85. fn main() {
  86. println!("{}", descriptive_probability(NewRelease));
  87. }
  88. ```
  89. We shouldn't ever hit the `_` case, so we use the `unreachable!()` macro to
  90. indicate this. `unreachable!()` gives a different kind of error than `Result`.
  91. Rust calls these sorts of errors *panics*.
  92. # Handling errors with `Option` and `Result`
  93. The simplest way to indicate that a function may fail is to use the `Option<T>`
  94. type. Remember our `from_str()` example? Here's its type signature:
  95. ```{rust,ignore}
  96. pub fn from_str<A: FromStr>(s: &str) -> Option<A>
  97. ```
  98. `from_str()` returns an `Option<A>`. If the conversion succeeds, it will return
  99. `Some(value)`, and if it fails, it will return `None`.
  100. This is appropriate for the simplest of cases, but doesn't give us a lot of
  101. information in the failure case. What if we wanted to know _why_ the conversion
  102. failed? For this, we can use the `Result<T, E>` type. It looks like this:
  103. ```rust
  104. enum Result<T, E> {
  105. Ok(T),
  106. Err(E)
  107. }
  108. ```
  109. This enum is provided by Rust itself, so you don't need to define it to use it
  110. in your code. The `Ok(T)` variant represents a success, and the `Err(E)` variant
  111. represents a failure. Returning a `Result` instead of an `Option` is recommended
  112. for all but the most trivial of situations.
  113. Here's an example of using `Result`:
  114. ```rust
  115. #[derive(Debug)]
  116. enum Version { Version1, Version2 }
  117. #[derive(Debug)]
  118. enum ParseError { InvalidHeaderLength, InvalidVersion }
  119. fn parse_version(header: &[u8]) -> Result<Version, ParseError> {
  120. if header.len() < 1 {
  121. return Err(ParseError::InvalidHeaderLength);
  122. }
  123. match header[0] {
  124. 1 => Ok(Version::Version1),
  125. 2 => Ok(Version::Version2),
  126. _ => Err(ParseError::InvalidVersion)
  127. }
  128. }
  129. let version = parse_version(&[1, 2, 3, 4]);
  130. match version {
  131. Ok(v) => {
  132. println!("working with version: {:?}", v);
  133. }
  134. Err(e) => {
  135. println!("error parsing header: {:?}", e);
  136. }
  137. }
  138. ```
  139. This function makes use of an enum, `ParseError`, to enumerate the various
  140. errors that can occur.
  141. # Non-recoverable errors with `panic!`
  142. In the case of an error that is unexpected and not recoverable, the `panic!`
  143. macro will induce a panic. This will crash the current thread, and give an error:
  144. ```{rust,ignore}
  145. panic!("boom");
  146. ```
  147. gives
  148. ```text
  149. thread '<main>' panicked at 'boom', hello.rs:2
  150. ```
  151. when you run it.
  152. Because these kinds of situations are relatively rare, use panics sparingly.
  153. # Upgrading failures to panics
  154. In certain circumstances, even though a function may fail, we may want to treat
  155. it as a panic instead. For example, `io::stdin().read_line()` returns an
  156. `IoResult<String>`, a form of `Result`, when there is an error reading the
  157. line. This allows us to handle and possibly recover from this sort of error.
  158. If we don't want to handle this error, and would rather just abort the program,
  159. we can use the `unwrap()` method:
  160. ```{rust,ignore}
  161. io::stdin().read_line().unwrap();
  162. ```
  163. `unwrap()` will `panic!` if the `Option` is `None`. This basically says "Give
  164. me the value, and if something goes wrong, just crash." This is less reliable
  165. than matching the error and attempting to recover, but is also significantly
  166. shorter. Sometimes, just crashing is appropriate.
  167. There's another way of doing this that's a bit nicer than `unwrap()`:
  168. ```{rust,ignore}
  169. let input = io::stdin().read_line()
  170. .ok()
  171. .expect("Failed to read line");
  172. ```
  173. `ok()` converts the `IoResult` into an `Option`, and `expect()` does the same
  174. thing as `unwrap()`, but takes a message. This message is passed along to the
  175. underlying `panic!`, providing a better error message if the code errors.
  176. # Using `try!`
  177. When writing code that calls many functions that return the `Result` type, the
  178. error handling can be tedious. The `try!` macro hides some of the boilerplate
  179. of propagating errors up the call stack.
  180. It replaces this:
  181. ```rust
  182. use std::fs::File;
  183. use std::io;
  184. use std::io::prelude::*;
  185. struct Info {
  186. name: String,
  187. age: i32,
  188. rating: i32,
  189. }
  190. fn write_info(info: &Info) -> io::Result<()> {
  191. let mut file = File::open("my_best_friends.txt").unwrap();
  192. if let Err(e) = writeln!(&mut file, "name: {}", info.name) {
  193. return Err(e)
  194. }
  195. if let Err(e) = writeln!(&mut file, "age: {}", info.age) {
  196. return Err(e)
  197. }
  198. if let Err(e) = writeln!(&mut file, "rating: {}", info.rating) {
  199. return Err(e)
  200. }
  201. return Ok(());
  202. }
  203. ```
  204. With this:
  205. ```rust
  206. use std::fs::File;
  207. use std::io;
  208. use std::io::prelude::*;
  209. struct Info {
  210. name: String,
  211. age: i32,
  212. rating: i32,
  213. }
  214. fn write_info(info: &Info) -> io::Result<()> {
  215. let mut file = try!(File::open("my_best_friends.txt"));
  216. try!(writeln!(&mut file, "name: {}", info.name));
  217. try!(writeln!(&mut file, "age: {}", info.age));
  218. try!(writeln!(&mut file, "rating: {}", info.rating));
  219. return Ok(());
  220. }
  221. ```
  222. Wrapping an expression in `try!` will result in the unwrapped success (`Ok`)
  223. value, unless the result is `Err`, in which case `Err` is returned early from
  224. the enclosing function.
  225. It's worth noting that you can only use `try!` from a function that returns a
  226. `Result`, which means that you cannot use `try!` inside of `main()`, because
  227. `main()` doesn't return anything.
  228. `try!` makes use of [`FromError`](../std/error/#the-fromerror-trait) to determine
  229. what to return in the error case.