20 ms·
Yes, 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, every
by Animats 12y ago
Yes, 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).
- burntsushi 12y agoIt's definitely not idiomatic error handling, but quickcheck uses a mechanism like you speak of: https://github.com/BurntSushi/quickcheck/blob/master/src/tester.rs#L403-L413 https://github.com/BurntSushi/quickcheck/blob/master/src/tes... (This is just implementation details---I'm not saying this is actor based!) This lets it handle failures that panic, and then shrink the witnesses to find (hopefully) minimal witnesses. :-)
- rdtsc 12y agoInteresting, thanks for the link! I'll have to look at that some more. This calls for a Rust actor library perhaps. Memory and type safety in Rust seems like might work well there (making sure memory is not accidentally shared between concurrency units -- really one of the main advantage of Erlang's VM).
- charlieflowers 12y agoWhy do you need a separate thread here? Is Rust's panic tied to the currently executing thread?
- burntsushi 12y agoKinda sorta. My knowledge is limited on the topic, but AFAIK, unwinding for Rust is designed to have at most one try/catch block per thread. That said, there is a `catch_panic` function (http://doc.rust-lang.org/std/thread/fn.catch_panic.html http://doc.rust-lang.org/std/thread/fn.catch_panic.html), but it's unstable. So in stable Rust, the only way to catch a panic is to spawn a new thread, I think.
- pcwalton 12y agoRust's thread library is designed to encourage this kind of programming. In fact, one of the goals of Servo is to use this pattern in a finer-grained way than existing browser engines do. (For example, if an image decoder crashes, wouldn't it be nice if you just got a broken image icon instead of a crashed tab?)
- burntsushi 12y agoI left out value judgments from my blog post, but not because I dislike error handling in Rust. In fact, I love error handling in Rust. I think it works quite smoothly. A healthy mix of combinators and the `try!` macro has really worked well for me.
- amelius 12y agoIndeed. Let's keep the fun in programming, and keep exceptions.
- mpdehaan2 12y agoYeah, this is interesting. While I like the look of Rust being every expressive, I love exceptions because they don't mean you have to plumb and error all the way through the program and can avoid tons of boilerplate - which in the end can make something (IMHO) a lot more readable. Now, checked exceptions in Java were not fun back in the day :)
- phaylon 12y ago> Exceptions have the good property that they can't be ignored - if they're not handled, you get a reasonable program termination. This would probably be the main point where I'd disagree. To get the same guarantees as you currently have, the exceptions would have to be checked exceptions like in Java. And, in contrast, the advantage (to me) here is that all error handling in Rust basically works like handling anything else. Personally, I'm rather fond of the way Rust does it. Which surprised me, coming from a dynamic background.
- wvenable 12y agoChecked exceptions turn error handling into nearly almost the multiple-return handling that Rust has. In my opinion, to achieve big advantages that exceptions offer, you should only have a small number of try/catch blocks. You only catch when you can reasonably expect to handle the error and that's it. Checked exceptions make you check for errors almost everywhere. Rust makes you check everywhere. They're almost the same thing. But I'll take Rust's method over checked exceptions any day; all is better than almost all. And for the type of projects Rust is built for, it's the right choice. But for error handling in general, if you don't care about the cost, unchecked exceptions are superior to both.
- benjiweber 12y agoChecked exceptions are so equivalent you can just translate between the two styles http://benjiweber.co.uk/blog/2014/03/22/checked-exceptions-and-streams/ http://benjiweber.co.uk/blog/2014/03/22/checked-exceptions-a...
- charlieflowers 12y agoCan you clarify this? Your first paragraph seemed to contradict your 2nd one -- I think I must have misunderstood you somewhere. I thought paragraph 1 boiled down to: "you shouldn't see any error handling code most places; only at the top." Then in the 2nd paragraph, I interpret "all is better than almost all" as: "I want to be forced to check all exceptions all the time, not just a few. (Meaning, I want error handling code everywhere)." Again, not being argumentative. Just asking for clarification.
- pcwalton 12y agoSome people need to use Rust in places where exceptions aren't allowed (because the unwind tables and cleanup code are too big). Those people include virtually all browser vendors and game developers. Furthermore, exceptions have this nasty codegen tradeoff. Either you make them zero-cost (as C++, Obj-C, and Swift compilers typically do), in which case throwing an exception is very expensive at runtime, or you make them non-zero-cost (as Java HotSpot and Go 6g/8g do), in which case you eat a performance penalty for every single try block (in Go, defer) even if no exception is thrown. For a language with RAII, every single stack object with a destructor forms an implicit try block, so this is impractical in practice. The performance overhead of zero-cost exceptions is not a theoretical issue. I remember stories of Eclipse taking 30 seconds to start up when compiled with GCJ (which used zero-cost exceptions) because it throws thousands of exceptions while starting. The C approach to error handling has a great performance and code size story relative to exceptions when you consider both the error and success paths, which is why systems code overwhelmingly prefers it. It has poor ergonomics and safety, however, which Rust addresses with Result. Rust's approach forms a hybrid that's designed to achieve the performance of C error handling while eliminating its gotchas.
- coldtea 12y ago>The performance overhead of zero-cost exceptions is not a theoretical issue. I remember stories of Eclipse taking 30 seconds to start up when compiled with GCJ (which used zero-cost exceptions) because it throws thousands of exceptions while starting. Then maybe the solution is to not have it throw thousands of exceptions while starting? And have them be, well, exceptional?
- pcwalton 12y agoAPIs have to be designed to allow that in the first place. For instance, the easiest way to check whether a file exists and open if it so is to try to open it and handle the error, because "look before you leap" can be racy. But in exception-based languages, the only way to do that is typically to catch an exception, because the core file I/O APIs throw exceptions on error.
- maxbrunsfeld 12y ago> I really want Rust to succeed, but I think they took a wrong turn with error handling. Wow, I have exactly the opposite impression. I am so excited by how elegantly error handling is done in Rust. > Having to write all that error handling code up front is going to be a big problem for the Agile crowd. I really disagree. At my last job (Pivotal Labs, definitely part of the 'Agile crowd'), large internal projects have been ported from Ruby to Go. There are a lot of things I don't like about Go, but one thing that everyone I worked with really enjoyed about it was the clarity and explicitness of the error handling. Exceptions are hard to reason about and hard to remember to handle; errors returned from functions are so simple. It seems like Rust's error handling has the good properties of Go's, but it allows for more abstraction because of Rust's more powerful type system. I think the Agile crowd that I've hung out with is going to love it.
- skybrian 12y agoThe difference seems to be that Go has a preferred way to do it: explicit case analysis and early returns. There are other approaches but they're used much less and rarely exposed in API's. Meanwhile, apparently the Rust folks can't make up their minds, so they support lots of different functional styles of error handling.
- maxbrunsfeld 12y ago> The difference seems to be that Go has a preferred way to do it: explicit case analysis and early returns. In other words, there is no way to abstract over the case analysis in Go. It sounds like you're saying this is a good thing. I think it's bad. > ... apparently the Rust folks can't make up their minds Wow, I'd say the opposite. In Go, the only thing all `error` objects have in common is the `Error()` method, which returns a description. If you want to investigate the causal chain of an error (to achieve what stack-traces give you in languages with exceptions), there is no standard way, even for errors in the standard library. Some errors are basically just strings, others are structs with other fields that you can access by using runtime type assertions. Rust, on the other hand, has the `Error` trait, which includes a `cause` method, returning the underlying error if one exists. This alone seems to me like an improvement in consistency over Go.
- oldmanjay 12y agoI'll agree that many people use "agile" as an excuse to skip handling errors correctly, and the end result of that attitude is very little error handling code, but I've never seen a robustly designed project that wasn't mostly error handling somewhere. The real trick is if the language gives you the ability to abstract over it in some way so that you can make the handling ergonomic in some way.
- tatterdemalion 12y agoUnless you need a custom error type for some particular intentional reason, it is currently very simple to instead throw Box<Error> to integrate all Errors into one type. I have not needed to unify error types into a custom type. Rust's error handling can be handled in a much cleaner and more expressive way than exceptions are handled and they are fully integrated into the type system. I don't know what advantages exceptions have.
- barrkel 12y agoMonadic composition of code (like the Result type shown) is semantically equivalent to checked exception handling, except with more syntactic ceremony. The 'and_then' is a continuation for the happy case, the 'or_else' is a continuation for the catch block. From my reading of the article, there is a mechanical transformation from exception-handling code to the continuation passing compositional style advocated. Checked exceptions have their problems - and I'm unconvinced on first reading that Rust has not got the same compositional problems without a whole bunch of extra complexity in parametric polymorphism - but the real problem is that most code shouldn't be dealing with errors low down in the stack. Code that makes the happy case verbose and forces you to continuously deal with the error case promotes either of two things: logging and then ignoring errors at a low level, where callers can't control the decisions; or Herculean efforts to transport errors up from deeply nested stacks all the way out, so that error passing code starts to dominate over code that works for a living.
- TD-Linux 12y agoFor me, coming from C, Rust exception handling feels very natural and obvious. Error handling in C usually involves returning either an error code, or having a sentinel value in the return type. Rust's Option type is an obvious extension, and ends up being more compact than C error handling code.
- Jweb_Guru 12y agoError handling is not supposed to be fun. It is hard. It doesn't stop being hard because you decided to hide it in the type signature. Point by point: > 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.... If the errors are internal implementation details that you don't want to expose (or you just don't feel like writing wrappers), and you don't want to handle them either, you can return `Result<T, Box<Error>`, as noted in the article. This requires all of no work on your part as long as other libraries are also returning instances of `Error` (and in general, they are), while also ensuring that your library returns an instance of `Error`. If your library defines its own meaningful errors, and you want to expose those to the user, then you will need to create a type and define `Error` for them, but you would also have to do the equivalent in any typed language with exceptions. If you additionally want them to be "top level" errors, but want to wrap other types of errors as the ultimate cause, you'll also need a single `From<Error>` implementation (from generic errors to your type) which in my experience is not even more code than a single catch-and-rethrow-as-another-type in a language with exceptions. (I bring this up mostly for the benefit of others, as it has been explained to you before. Perhaps when you wrote your library `Error` hadn't been stabilized yet, but all of what I said above has been possible in Rust for many months now). > 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. The "Agile" approach to error handling is `unwrap()`. It's not recommended in libraries because they violate the contracts the libraries expose, a problem they share with unchecked exceptions in other languages. > All this error machinery is in Rust to avoid exceptions. That may have been a mistake. Preferring sum types is not just true in Rust, where one might speculate that it's because it lacks `catch`: my impression is that in all three of Haskell, Scala, and OCaml, which support both, public opinion has moved steadily away from exceptions and towards `Either` for error handling. This is quite striking given that there are good reasons to believe that exceptions would be popular in those languages: in Haskell because pure code suffers from relatively fewer exception safety issues, in OCaml because the exception implementation is highly optimized, in Scala because the prevailing ecosystem (where most of the employees are drawn from) uses exceptions for error handling. The fact that all of these communities, given both options, tend to use sum types, suggests to me that the theoretical benefits of this approach (many of which you covered) are also practical for many people. > Exceptions have the good property that they can't be ignored - if they're not handled, you get a reasonable program termination. In a recent paper, the following three things were found to have led to 35% catastrophic production failures: https://www.usenix.org/system/files/conference/osdi14/osdi14-paper-yuan.pdf https://www.usenix.org/system/files/conference/osdi14/osdi14...: > (i)the error handler ignores explicit errors; (ii) the error handler over-catches an exception and aborts the system; and(iii) the error handler contains “TODO” or “FIXME” in the comment. It sounds like people do a fine job of ignoring exceptions. Moreover, it seems to me like what you are advocating (catching `RuntimeError` or something equally generic, where you can't possibly take an explicit corrective action, but not terminating the program) is precisely what ended up causing a lot of these bugs. In any case, it's not likely that you'll out and out forget to handle a `Result` in Rust. You can't even try to access the inner value without handling errors, and if you just don't use it (because you don't care about the value) Rust generates a warning (people generally pay attention to Rust warnings, since there are relatively few of them). If you `unwrap()` it, it's even easier to find where you aren't handling your errors properly--you just grep for `unwrap()`. In my experience, people ignore errors far less in Rust than in any other language I've worked with, because it actually makes them explicit when they happen, rather than propagating them down to a consumer who has no idea what to do with the error. > If there's a reasonable exception hierarchy, you can catch an exception near the root of the tree and get all subsidiary exceptions. I also am interested to hear why you believe that hierarchical error types make sense: errors seem to me to be one of the absolute worst fits for the classical inheritance model. They very rarely have any shared behavior or state that isn't also on `Error`, and trying to fit them into a hierarchy is an exercise in frustration that is undertaken for the sole purpose of avoiding multiple catch clauses--they very rarely compose and are even more rarely extensible. More often, people just give up and use a single type with a String, or--equally commonly--simply `catch Exception` whenever they expect an exceptional condition to be raised without bothering to check the type at all. > you have to combine error types yourself. And coming full circle... no, you don't :) > I really want Rust to succeed, but I think they took a wrong turn with error handling. You have repeated both this sentiment and the bulk of your comment in many, many posts now. I believe that you are sincere in your desire for exceptions (even if I disagree with it), but I don't think you or anyone else seriously believes that not making catchable exceptions the default error handling technique is going to make or break Rust adoption, especially when its primary target audience is known for routinely disabling exceptions to avoid dealing with exception safety and performance issues.
- _pmf_ 12y ago> This may be a major drag on Rust adoption. Meh. Agile or robust; sometimes people have to choose.
- nostrademons 12y agoI get the sense that Rust isn't aimed at the Agile crowd. It's intended to be a replacement for C++. If you were building an Agile app, you would probably write it in Python first and then once you have the overall architecture in place, rewrite certain libraries (like the parser or low-level networking) in C++. Now you'd rewrite them in Rust instead. Or when your RSS reader gets mainstream adoption and is used by millions of people, you rewrite the whole thing in Rust. Under this use-case, the verbosity is still a pain, but it's not a major drag on adoption. You already know what you're building and have something that basically works, just slowly, so you don't have to pay the cost over and over again in product iterations. And your expectation isn't "Oh, I'm just trying something out, why can't it let me get to the fun part?", it's "Well, this sucks, but it's what I'm being paid for and at least I'm solving a hard technical problem with the most performant code I can."