20 ms·
Error handling in Rust
- steveklabnik 12y agoOne of the reasons I'm really excited for stability is that people can start to write things like this, knowing that the effort is worth it, as it won't suddenly stop working tomorrow. Next week, burntsushi and I are going to talk about rolling this into the official documentation.
- coldpie 12y agoYes, I'm very glad to see Rust stabilizing. I wrote a few personal projects in it earlier this year, and now none of it compiles. I'm very excited for Rust, but the instability has put me off learning in-depth.
- simcop2387 12y agoAs of tomorrow it should finally be over that kind of instability for good. I've been doing some tiny things to learn the syntax and how to work with it but I've had the same experience. Really can't wait for the release tomorrow.
- oinksoft 12y agoThat sounds terrible, is Rust that unstable in practice today? I remember hearing that the language had mostly stabilized at the end of 2014, but anecdotes like yours are discouraging.
- burntsushi 12y agoThere were some expected periods of instability at the beginning of this year, but recently, there's been little to no breakage. I know because I maintain several crates and I'm not getting pinged every day with new PRs fixing my code. :-)
- simcop2387 12y agoThere had been some breaking changes going on towards the 1.0 release. The first alpha to clean that up was in January of this year which really started the move to stabilize a lot of things, but there were still some breaking changes (I know there were a few around IO). It went beta back in April and there haven't been any serious breaking changes since (that I know of, I'm only following things not a rust developer). Tomorrow it'll be released as the 1.0 stable version that from then on you won't have any breaking changes (until 2.0, or whatever the next version is). That's not too unusual for a language that has been evolving the way rust has, you just can't avoid breaking changes for a while until you actually figure out what works the way you're after. But kudos to the rust team for getting it this far; I can't wait to see all the celebration tomorrow.
- tatterdemalion 12y agoRust is completely stable tomorrow. :)
- coldpie 12y agoI wouldn't call it terrible. It was a language under development, I expected breakage. They're stabilizing now for a final release, so it shouldn't be an issue going forward.
- Animats 12y agoYes, it really is that complicated. It's quite elegant in its way. If you start from the proposition that you don't want exceptions, you don't want Null, everything is strongly typed, error types are not hierarchical, and functional programming with lambdas is reasonable within sequential code, this is where you end up. It's logical, but not fun. I wrote an RSS reader in Rust, and all the code required to compose all the error types (I/O, HTTP, XML, RSS, date formats) into a custom error type is as bulky as the modest amount of code that does the useful work. That's not a good thing. Having to write all that error handling code up front is going to be a big problem for the Agile crowd. This may be a major drag on Rust adoption. All this error machinery is in Rust to avoid exceptions. That may have been a mistake. Exceptions have the good property that they can't be ignored - if they're not handled, you get a reasonable program termination. If there's a reasonable exception hierarchy, you can catch an exception near the root of the tree and get all subsidiary exceptions. (It took three major revisions of exception handling before Python got that right, but it finally did.) Rust doesn't have an error hierarchy like that; you can't just check for "RuntimeError" or "EnvironmentError" and get all the more detailed errors. You have to combine error types yourself, as the article shows. I really want Rust to succeed, but I think they took a wrong turn with error handling.
- deleted 12y ago[deleted]
- rdtsc 12y agoSo far the best error handling pattern I like is actor based (like Erlang for example), where you usually code the main "happy" path separately, where the business logic is cleanly seen, perhaps the error handling is an external supervisor or monitor process. That works for higher level use cases (like handling http requests, parsing, talking to database) and works especially well with heap isolated concurrency units (processes). Maybe it doesn't work for a language that can interface with hardware drivers ... But still wonder how much of an anti-pattern that would be in Rust -- spawn a separate thread, and then do all the IO, HTTP, XML, RSS parsing in a clean way. Then let it panic and somehow find the reason for panic in the original main thread. Then decide there what to do (exit, log, bubble up failure etc).
- coldtea 12y agoPerhaps naive question: is there a language where errors are automatically returned from a function (in lieu of exceptions)? So if you have a function x that has some unhandled "exception" thrown, what it does is it returns an error value at that point to the caller (instead of actually throwing an Exception). Does that exist?
- tel 12y agoI believe you can't have that happen universally since then you don't get the benefit of having exceptions bubble at all—you're just de facto operating in an error monad. On the other hand, if it's not universal then you have to set boundaries where the exception to value transition occurs and this is "just" a catch block.
- coldtea 12y ago>I believe you can't have that happen universally since then you don't get the benefit of having exceptions bubble at all—you're just de facto operating in an error monad. I was thinking something like you get an Optional, and you check it. If you use it without a check (e.g. something like "try" in Rust), and it's an error value, then it "explodes" again and bubbles up.
- tel 12y agoThe mechanics of that are easily captured with a monad, but baking it into the natural semantics of the language would be a neat experiment, I agree.
- tatterdemalion 12y agoThis is what Rust does. Not to try to summarize the article, but functions which could 'throw exceptions' instead of returning type T, return type Result<T, E>, where E is an Error type. The try!() macro wraps an expression that could be an error, returning early with the error value if it is an error and evaluating to the non-error value if it is not an error. EDIT: Oh, I see, you mean without having to declare it.
- 12y ago
- msie 12y agoWhere does the n and err values come from? fn double_number(number_str: &str) -> Result<i32, ParseIntError> { match number_str.parse::<i32>() { Ok(n) => Ok(2 * n), Err(err) => Err(err), } }
- maxbrunsfeld 12y agoFrom the left-hand side of the `=>` arrows in the `match` expression.
- msie 12y agoI know that. Where do they come from before that?
- steveklabnik 12y agomatch number_str.parse::<i32>() { This matches on the return value of parse, which is an Result<T>. It can have two values: Err(E), or Ok(T). Ok(n) => Ok(2 * n), This line matches an Ok(T), and binds the value of type T to n, which can then be used on the right hand side. Err(err) => Err(err), this line matches an Err(T), and binds the value of type T to err, which can be used on the right hand side. The right hand sides re-wrap these values into another Result.
- phaylon 12y agoNitpick: Result<T, E> instead of Result<T> assuming Result is std::result::Result.
- steveklabnik 12y agoAhh yes, thank you.
- msie 12y agoThanks!
- 1_player 12y agoAwesome article, but I'm stuck on the "error-double-string" example: ... argv.nth(1) .ok_or("Please give at least one argument".into()) .and_then(|arg| arg.parse::<i32>().map_err(|err| err.to_string())) ... What is str::into? I find the documentation is really hard to navigate for a Rust newbie like me: here's what I've tried: 1) Search "into" on the API docs. I find (https://doc.rust-lang.org/std/convert/trait.Into.html#tymethod.into https://doc.rust-lang.org/std/convert/trait.Into.html#tymeth...) and see that str implements this trait to convert it to a Vec<u8>. Not seeing the need for a conversion to Vec<u8> I... 2) Search "ok_or": I find (https://doc.rust-lang.org/core/option/enum.Option.html#method.ok_or https://doc.rust-lang.org/core/option/enum.Option.html#metho...) but I still don't see why the string has to be converted to Vec<u8>. 3) Maybe literal strings are Vec<u8> and into() just is used to convert a Vec<u8> to str. Can't find any documentation on that, and seems fishy if it were the case. 4) Try googling "rust str into" with useless results. Not Rust's fault here :) I haven't used Rust yet but often try to read other people code and understand what's going on, and everytime I hit the API docs I'm filled with despair that I can't find what a function is supposed to do. Again, I'm a noob. I must be doing something wrong..
- steveklabnik 12y agoOne thing you can do when you're confused about a type is to remove the call, and see what happens: error: mismatched types: expected `core::result::Result<_, &str>`, found `core::result::Result<i32, collections::string::String>` (expected &-ptr, found struct `collections::string::String`) [E0308] hello.rs:6 .and_then(|arg| arg.parse::<i32>().map_err(|err| err.to_string())) ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ hello.rs:6:25: 6:74 help: pass `--explain E0308` to see a detailed explanation In other words, without the call to `into()`, we expected a &str, but got a String. This `into()` call is the first one that you found, but, through some magic, it's not clearly obvious, it's true. The secret is Into's opposite, From: https://doc.rust-lang.org/std/convert/trait.From.html https://doc.rust-lang.org/std/convert/trait.From.html There's a generic implementation in the standard library: impl<T, U> Into<U> for T where U: From<T> { In other words, anything that implements From, implements Into as well. So generally, things just implement From, and take advantage of this blanket implementation. With this knowledge, this From implementation makes sense: impl<'a> From<&'a str> for String We can convert From a String to a &str, and hence, we can convert a &str Into a String. This kind of type shenanigans is _very_ powerful, but admittedly, a bit confusing.
- madez 12y agoThe example io-basic-error-custom and the first version of error-impl have the same content but different names, while the reference just above the first version of the latter points to the former. Is this intentional? It confused me for a second. I know this is nitpicking, just asking. And, thank you steveklabnik, pcwalton, and other contributors of Rust for working in the open and answering our questions here. Thank you burntsushi for your great post.
- burntsushi 12y agoAh, hmm. They have different content. error-impl: https://github.com/BurntSushi/blog/blob/master/code/rust-error-handling/src/bin/error-impl.rs https://github.com/BurntSushi/blog/blob/master/code/rust-err... io-basic-error-custom: https://github.com/BurntSushi/blog/blob/master/code/rust-error-handling/src/bin/io-basic-error-custom.rs https://github.com/BurntSushi/blog/blob/master/code/rust-err... The key is that the code is spread out over multiple blocks in the article. I need a better literate programming tool than hacky Python...
- madez 12y agoI looked at it again and now I see that the code examples don't necessarily constitute the whole file. And the parts in question happen to be the same in both files. My fault. Maybe it would be interesting for the reader to see the number of the lines of the shown code, something like "error-impl.rs, lines 3-12 out of 51".
- burntsushi 12y agoYeah, that would be a nice improvement. Some day, I will need to improve my literate programming tool: https://github.com/BurntSushi/blog/blob/master/scripts/rust-from-blog https://github.com/BurntSushi/blog/blob/master/scripts/rust-... :P
- extropy 12y agoHow about separate the processing code from error handling code into a block of it's own. Like this: fn file_double<P: AsRef<Path>>(file_path: P) -> Result<i32, String> { let mut file = File::open(file_path); let mut contents = String::new(); let read_Result = file.read_to_string(&mut contents); let n = contents.trim.parse::<i32>(); let result = 2 * n; error_handling { file: None => Err("Failed open file"), read_Result: Err(err) => Err(err), n: Err(err) => Err(err), _success: Ok(result) }; } The compiler would then convert each error handling case into early return statements in the places where assignment is made to the specified variable.
- burntsushi 12y agoI'm not sure how that's supposed to work. For example, you have `file.read_to_string`, but in your code, `file` is a `Result`. So you'll need to use `map` I presume. I personally like the style that `try!` encourages.
- charlieflowers 12y ago> The power of Error comes from the fact that all error types impl Error, which means errors can be existentially quantified as a trait object. This manifests as either Box<Error> or &Error. It took me a couple of minutes to figure out that this means: "you can have heterogeneous collections of errors, and you can use them 'polymorphically' without knowing their concrete type." In other words, you can use Error as a "trait object." I don't think a newbie to Rust would follow the language in the article here. (Just a suggestion to help improve an outstanding article).