11 ms·
Exceptional results: error handling in C# and Rust
- noelwelsh 11y agoGood post. Not capturing a stack trace is a Rust specific thing -- this is easy to do in Scala, for example, and still maintain the benefits of monads + algebraic data types. I'm sure Rust will get similar utilities with time. The main issue I have with this technique is the higher mental overhead when getting started. That goes away with a bit of practice.
- seanmcdirmid 11y agoScala gets stack traces automatically from the JVM though, along with much of its debugging support. The Rust team will have to do this all by themselves, being a natively compiled language and all.
- noelwelsh 11y agoSure. The author mentioned lack of stack traces as a downside of the technique. I wanted to clarify this was Rust specific (and likely to change).
- masklinn 11y agoYou can get stack traces on panics by running with RUST_BACKTRACE=1. I don't know that it makes much sense on Error objects though, there's no requirement that they're even able to store backtraces, and collecting backtraces any time an error object is created would be really expensive and would make the runtime a dependency of errors.
- seanmcdirmid 11y agoMost VMs put most of the overhead of stack creation at where the error is created, so it usually works out fine (throw is expensive, everything else is cheap). Stack traces are usually dependent on whatever debug symbols are loaded, so in the CLR you'll get huge blank spaces if an exception propagates through some dynamically generated or even native code. Just printing stack traces is a distraction though. The only thing that is required that on an exception, the entire stack above the the exception site can be inspected in the debugger.
- masklinn 11y agoThat's a completely different concern, and it only makes sense on panics, not any time an Err result is created.
- seanmcdirmid 11y agoAnd how do you tell where an error originated without a panic being called? Is the programmer expected to just instrument the their code to put the panic in as soon as possible? Anyways, this is a well-known problem with monadic error handling, and one of the main reasons it doesn't get more widespread adoption.
- masklinn 11y ago> I'm sure Rust will get similar utilities with time. Unlikely. Scala gets tracebacks for Try because the left arm stores a JVM Throwable, and throwables reify a stacktrace during initialisation. For Rust, this would mean: * Result's Err mandates an Error (currently has no trait bound at all) * Errors must be able to store a traceback * Error/Result requires rt in order to collect a stacktrace * Rather than stack-allocating a struct or two, Err results now require significant heap allocation and data collection completely breaking existing usage patterns
- seanmcdirmid 11y agoAs long as Err results are only created under exceptional circumstances, there should be no performance hit right? This is one significant reason why errors should get a path separate from normal return values, but that isn't the case in Rust (or monadic error handling in general, which doesn't really consider debugging).
- noelwelsh 11y agoI'm not suggesting `Err` stores a backtrace. I am suggesting that the programmer could choose to store a backtrace in the error objects they choose to store in an `Err`. I don't do this in my Scala code because I rarely find I need a backtrace. (I don't use `Try` for reasons described here: http://underscore.io/blog/posts/2015/02/23/designing-fail-fast-error-handling.html http://underscore.io/blog/posts/2015/02/23/designing-fail-fa...)
- masklinn 11y ago> I am suggesting that the programmer could choose to store a backtrace in the error objects they choose to store in an `Err`. That's already possible, though it requires nightly as it's an unstable "feature": http://doc.rust-lang.org/stable/std/rt/backtrace/index.html http://doc.rust-lang.org/stable/std/rt/backtrace/index.html This will collect a stacktrace in the provided buffer, the result can then be stored in whatever object the developer wants (likely after decoding it to a String): http://is.gd/tOD8Ho http://is.gd/tOD8Ho
- Khao 11y agoThe author is painting a pretty bad picure of C# error handling that isn't close to reality. In reality, you would never call uint.Parse and let the exception bubble up, you'd call uint.TryParse and handle the logic for failure in the method. There is almost always a way to write your code so it doesn't throw exceptions. I'm working on a pretty large C# codebase for a SaaS website and by doing "find in all files" the keyword "catch" I came up with 174 references. For hundreds of thousands of lines of code, we have had to manually catch and handle exceptions only 174 times.
- vitalyd 11y agouint.Parse vs TryParse misses the point. It's very true that doing proper error handling in C# requires more diligence and attention. I know people like to harp on checked exceptions in java, but if used properly, they at least help with the discoverability aspect. The fact that you have 174 catch blocks in a very large codebase only reinforces the blog's point, which is you may be missing error handling blocks or you just have very general handlers.
- Khao 11y agoWe don't really do catch-all blocks and our app is monitored on New Relic where we almost always have a 0% error rate (rarely we get <1%, most often related to a new commit that we can fix right away) The only places where we need good exception handling is when doing I/O (network and filesystem). If you have proper layers to handle those things (with queuing/retrying/logging) you end up with a large codebase with very little places where you have to handle exceptions. Anything that is user-input we use TryParse and we do proper validation on the data before doing anything with it. This method is makes it easier to read because you know what the intent is better than doing parse/catch exception in my opinion.
- vitalyd 11y agoOh, I agree that TryParse is much better than Parse for cases where parsing is expected to fail. But that doesn't detract from having better error handling capabilities in places where it is needed (e.g. i/o). A lot of the .NET i/o APIs will throw 4-5 different types of exceptions, and as the article states, you need to cross reference docs to see which exceptions are possible on certain calls. It's easy to forget or miss because compiler will not care.
- jeswin 11y ago> I have written plenty of C# code that deals with exceptions, and it is a pain to do it correctly. Apart from null, it might very well be the biggest design mistake of the language. In user code (as opposed to framework code), Typed Exceptions are overrated. Let's take these two cases: 1. End-User: Doesn't care if the Exception is a ParseException or an InvalidVersionException. Exception("Invalid number") and Exception("Version should be higher") is just as good enough for a message. Basically, for the end-user, the app crashed and that's it. 2. Programmer: Will have to open the debugger or check the code anyway. I get it that it's useful in some cases, when you wanna send back some structured data to the caller. But in the vast majority of cases, the plain Exception class and Stack Traces suffice.
- AndrewDucker 11y agoAgreed. I rarely need a typed exception. The purpose of the exception is to say "Stop doing what you were doing, and head up the stack until you find a point where the work can recover from this and carry on." Generally speaking, that point doesn't care why the bunch of stuff five levels down went wrong. It just wants to report the error, and then either carry on with something, or let the user know what the problem was and decide if they want it to carry on. Very occasionally, the actual type of the exception is useful. But mostly I just don't care about typed Exceptions.
- vitalyd 11y agoSo this is more akin to panics, where you don't really care about handling the error but rather want to stop dead in the tracks. But take something like .NET's SocketException, which contains a SocketErrorCode property; you may very well want to take different action depending on the type of error this is. This may be as simple as changing the text of the error shown to user (with suggestions on how to fix), but could also be some code based recovery that takes different action depending on the type.
- scardine 11y agoI guess Python is an exception to this rule. Typed exceptions are not only idiomatic but deeply ingrained into the language core. Even basic primitives like loops use exceptions to control flow (StopIteration).
- pornel 11y agoInteresting case is that Rust's cmp::max() doesn't support floating-point numbers, because maximum is undefined for Inf and NaN. For floats there's partial_max() which returns Option<f32>. It makes sense, but it never crossed my mind before that a simple max() function can fail. It's also PITA to error-check such a simple thing, but somewhat surprisingly there's also f32.max() that works on garbage-in garbage-out principle.
- dfkf 11y agoHuh, author even uses exceptions as a part of normal workflow, instead of checking if "previousVersions" list is empty before calling Min on it he instead catches InvalidOperationException. I don't want it to look like an ad hominem argument, but... Anyway, C# authors had Java in sight when designing the language and after some contemplation they didn't include checked exceptions in the language. And their main argument is that in the vast majority of cases ignoring the exception and allowing it to propagate further up the stack is exactly what you want to do, simply because there is nothing you can do about it but to log it and tear down the entire object graph or write an error message to the user.
- stinos 11y ago> propagate further up the stack is exactly what you want to do This is an important point imo. It is actually one of the ways you can describe to a non-programmer why it can be so hard to write typcial desktop software which never ever crashes (as in 'unhandled exception' dialog): huge amounts of time would be wasted to figure out for each and every single statement what can go wrong and how to handle it. Seriously, I've been at meetings where more time was spent on discussion on how to deal with/present to the user some obscure once-in-a-lifetime error than on actually fullfilling requirements.
- wvenable 11y agoI have a desktop app that has a single exception handler at the event loop. It's amazingly robust. That file you're trying to save is locked? Network location went away? Doesn't matter. It displays the error in a dialog box (so you know what went wrong) and returns the user to the app. Whatever operation they were doing, they can just try again. Any cleanup is performed automatically and the application, without really any effort, is always in a stable state. That's how exceptions are supposed to work. The wack-a-mole attempt at ensuring you "handle" every case is wrong. The problem, in my opinion, is that most programmers have been so brain damaged by Java that anyone exposed to that way of programming can't see how exceptions are supposed to work. Java not only makes you try/catch/declare everything but also makes you use exceptions for non-exceptional operations. A perfect storm.
- SigmundA 11y ago"Can this method throw? Should I catch a PathTooLongException here? And while the .NET framework is documented to remarkable detail, this is rarely the case for third-party libraries or in-house code. At the bottom of the call stack, you just have to assume everything may throw. " Isn't this true for all languages in one form or another? Go and Rust have "panics" Any code might fail exceptionally, stack overflows and out of memory conditions come to mind as relatively common ones. The difference here is that C# treats more kinds of things exceptionally than Rust or Go. This seems to have more to do with Rust and Go ability to more easily return multiple types from a method/function and a philosophy of opt-in vs opt-out on handling an error. I am used to C#/javascript so exceptions with try catch are very natural to me. Writing robust programs always involves handling everything one way or another. Even out of memory conditions can be handled and recovered if your always thinking that everything can throw. The null issue is interesting, I like null, I like undefined with null even better in javascript. I always seem to need to encode something has no value or something was never even set vs picking a valid value as a special "no value" i.e. int.MaxValue or whatever. The only thing I would change in C# and javascript is null lifting object.property should not throw if object is null same with foreach over null object. They are adding the ?. for that but you need to explicitly do it, NullReferenceException is far to common in C# from those two situations explicitly. I belive Objective-C did some kind of null lifting where sending messages to null objects don't throw.
- masklinn 11y ago> Isn't this true for all languages in one form or another? Go and Rust have "panics" Any code might fail exceptionally, stack overflows and out of memory conditions come to mind as relatively common ones. The concern does not make sense in Rust, Rust's panics can not be caught and will kill the current thread. > The difference here is that C# treats more kinds of things exceptionally than Rust or Go. Or it treats exceptions much less exceptionally than they do (Python being even further along on that axis), a C# exception is at best "uncommon". > This seems to have more to do with Rust and Go ability to more easily return multiple types from a method/function Rust doesn't use MRV for results, Result is a single struct (technically an enumerated type which can contain either a "valid result" or an "error result", not both). > I belive Objective-C did some kind of null lifting where sending messages to null objects don't throw. Not in the sense you think, Objective-C's nil is simply a black-hole, messages send to it don't do anything and return nil. It's possible (though not probably not recommended) to opt Smalltalk or Ruby[0] into this behaviour, because nil is a standard object not a magical special value (and both languages have open classes). [0] http://blog.rubyenrails.nl/articles/2008/02/29/our-daily-method-18-nilclass-method_missing http://blog.rubyenrails.nl/articles/2008/02/29/our-daily-met...
- raphaelj 11y agoI love monadic error handling too, but not for the reason that the author cited. The fact that you know exactly what errors a function can throw is not an unique feature of monadic errors: in Java, you are required to explicitly list exceptions that a function can throw (checked exceptions), and you must handle every exception when calling the function. The real feature of monadic error handling is that error handling become composable. Imagine that you want to write a function that accepts three character-encoded integers and that you want this function to return the first integer it successfully parsed. With exceptions, you will probably use a parseInt function with a type similar to: fun parseInt(String) -> Int throws ParseException And you will write the function like this: fun getFirstInt(String a, String b, String c) -> Int throws ParseException: try: return parseInt(a) catch e1: try: return parseInt(b) catch e2: return parseInt(c) Now take a language supports algebric data types (like Haskell, Rust, Scala or OCaml). The parseInt function will probably have a type similar to: fun parseInt(String) -> Result<Int, ParseException> You will probably define a simple operator to manage the pattern if it fails, try that instead before implementing the getFirstInt function. Lets call this operator <|> (it's its name in Haskell): fun operator <|>(Result<r, e> left, Result<r, e> right) -> Result<r, e>: match left: Ok(r) -> return Ok(r) Error(e) -> return right With this operator, getFirstInt could be implemented as simply as fun getFirstInt(String a, String b, String c) -> Result<Int, ParseException>: return parseInt(a) <|> parseInt(b) <|> parseInt(c) I think that the fact that you can write you own error handling operator is the killer feature of monadic error handling (and monadic programming in general). It makes the enforced handling of errors really painless (while it's like hell in Java where every exception must be handled). It's almost impossible to create this kind of operators with exceptions because they are not a return value, and thus can't be handled in expression. With monadic error, handling operators are just plain old functions.
- masklinn 11y agoJust a note, Rust's error handling is not monadic because Rust doesn't have monads because it doesn't have HKTs, I guess we could call it "reified" though.
- louthy 11y agoWhilst some of the issues with C# are valid, it's totally possible to do monadic error handling in C#, I wrote an entire library to facilitate that [1]. In fact the big win of monadic error handling is the composable nature of monads: Here's a function that throws an error on odd numbers: Try<int> Number(int x) => () => { if( x % 2 == 0 ) return x; else throw new Exception("Any exception"); }; Here the monadic computation succeeds, and 'res' holds 1000: var res = match(from x in Number(10) from y in Number(10) from z in Number(10) select x * y * z, Succ: x => x Fail: 0); Here the monadic computation fails, and 'res' holds 0: var res = match(from x in Number(10) from y in Number(9) from z in Number(10) select x * y * z, Succ: x => x Fail: 0); If you don't want to use it in a LINQ expression then you can just say: var res = Number(10).IfFail(0); There's also mention of the null problem, which obviously is a major problem with the language (and framework), but it can be tamed somewhat with Option<T> and TryOption<T>: TryOption<int> Number(int x) => () => { if( x % 2 == 0 ) { if( x > 10 ) None; else return Some(x); } else { throw new Exception("Any exception"); } }; Here the monadic computation succeeds, and 'res' holds 1000: var res = match(from x in Number(10) from y in Number(10) from z in Number(10) select x * y * z, Some: x => x, None: 0, Fail: 0); Here the monadic computation fails, and 'res' holds -1: var res = match(from x in Number(10) from y in Number(9) from z in Number(10) select x * y * z, Some: x => x, None: 0, Fail: -1); Here the monadic computation also fails because a None is returned, so 'res' holds 0: var res = match(from x in Number(10) from y in Number(20) from z in Number(10) select x * y * z, Some: x => x, None: 0, Fail: -1); So as you can see, using monadic error handling is doable in C# with the right tools. It certainly takes a bit more discipline from the programmer, but it's definitely worth it. It also makes your code declarative. A function that looks like this: TryOption<string> DoStuff(); ... clearly declares that the function may: Succeed, return 'no value', or fail. So you should deal with all 3 possibilities. In contrast, this doesn't give that information to the programmer: string DoStuff(); [1] https://github.com/louthy/language-ext https://github.com/louthy/language-ext
- mamcx 11y agoI have building a toy language and about this I have wondering if is better to think in errors exactly with normal values. So, my functions are ALL like this: fun sample= StdOut(Str) | StdErr(Int) do if GoodLuck() do return "Yeah!" fail 1 ie: fail is exactly like return, is just a way to split between Ok values and Err values. If the client wanna catch them: result = sample() # Get the Ok value. if the Err value is returned, then trow like in exceptions result != sample() # Get the Err value, not trow result, err != sample() #Get both What do you think?
- TheLoneWolfling 11y agoI think that I don't like your function syntax, but meh, that's kind of irrelevant. So you're basically just using exceptions as syntatic sugar for return codes. Works reasonably well, I suppose.
- mamcx 11y agoThe syntax is no the final. I'm go after a python/julia/elixir like syntax.
- TheLoneWolfling 11y agoWell, it's not there yet. That being said, I don't particularly like the overloading of `!=` there. I like the idea of a shortcut meaning "call this function and get the error value", but I wouldn't use `!=` for it. Perhaps take a page from Lua's book and use `_` as a throwaway variable. So `a = foo()`, or `a,b = foo()`, or `_,b = foo()`.
- mamcx 11y agoOh, great suggestion... and so obvious...
- masklinn 11y ago> I have building a toy language and about this I have wondering if is better to think in errors exactly with normal values. That's exactly what Rust (to keep with TFA) does. Result is not really special, its core is just enum Result<T, E> { Ok(T), Err(E) } > What do you think? That the code doesn't make sense, the result and the error should be exclusive propositions, why would you get both a result and an error when the function should return either one or the other?
- wvenable 11y agoI find the opinions presented in this article are far too common these days in completely misunderstanding exceptions. "The consequence, when you want to write robust software in C#, is that you have to keep an MSDN tab open at all times. Can this method throw?" First of all, assume every method can throw. Just do it. It's either true or could be true in the future when someone changes that method. Maybe it doesn't use the network today but tomorrow it calls out to a webservice. So all methods throw. And forget knowing what exceptions they might throw. That's an implementation detail and we want to hide implementation details. "Should I catch a PathTooLongException here?" No, you shouldn't. What are you going to do any differently with that than you would FileIsLockedException or NetworkIsDownException or HarddriveIsCorruptException? You wouldn't do anything differently. Show the user the ErrorMessage in the dialog and allow them to restart whatever operation was in affect. Let them choose a shorter path, close Excel, plug their Ethernet cable back in, or whatever. Trying to play wack-a-mole is a fools errand. Put MSDN away, you don't need it.
- dcsommer 11y ago> No, you shouldn't. What are you going to do any differently with that than you would FileIsLockedException or NetworkIsDownException or HarddriveIsCorruptException? You wouldn't do anything differently. Show the user the ErrorMessage in the dialog and allow them to restart whatever operation was in affect. Let them choose a shorter path, close Excel, plug their Ethernet cable back in, or whatever. I don't think this approach works in general. Server software, at least, needs to automatically handle all these different failure modes in potentially unique ways.
- wvenable 11y agoIf you are aware of particular situation, you can handle it. If you aren't aware of a particular situation at best you log the problem and skip the operation. That's pretty straight forward and is still the same approach. For example, I might just catch every single Network exception, log it, add a timeout, and retry the operation. I'm not playing wack-a-mole and I don't care in the handler which of the thousands of methods called in my operation actually raised the exception. The point is one should not be looking at what exceptions the methods throw but instead what exceptions can be handled. One set is very large the other set is very small. This applies equally well to server software.
- detrino 11y agoBoth exceptions and results are important for software architecture. The lack of the former leads to an oversimplification of interfaces in languages with only the latter. The author hit upon an example that is probably better written using results. But guess what? A C# programmer would write it that way too. See the TryParse methods found all over the C# standard library. On the other hand, what would a Rust programmer do to handle an out of memory situation? That would be too pervasive with the result approach so it has been culled from all interfaces. Also, nullable reference types are a separate issue.
- kibwen 11y agoThe point that you're glossing over it that Rust forces you to acknowledge the existence of errors, either by working with Err types or by using .unwrap() to terminate the thread in the event of an error. The existence of both Parse and TryParse in C# indicates a trend of allowing to errors pass silently by default, which ultimately results in surprise runtime failures. > On the other hand, what would a Rust > programmer do to handle an out of memory > situation? Let's ask MSDN what a C# programmer would do: "This type of OutOfMemoryException exception represents a catastrophic failure. If you choose to handle the exception, you should include a catch block that calls the Environment.FailFast method to terminate your app and add an entry to the system event log" https://msdn.microsoft.com/en-us/library/system.outofmemoryexception%28v=vs.110%29.aspx https://msdn.microsoft.com/en-us/library/system.outofmemorye...
- detrino 11y agoI'm not glossing over it, I said that this is better written using results. Complaining about the existence of Parse is like complaining about the existence of unwrap in Rust. C++ (another systems language) is probably a better comparison for out of memory.
- kibwen 11y agoMoving my ninja edit down here into a reply: On modern systems it's not possible for an application to know when memory has been exhausted, because of virtual memory and overcommit (http://www.win.tue.nl/~aeb/linux/lk/lk-9.html#ss9.6 http://www.win.tue.nl/~aeb/linux/lk/lk-9.html#ss9.6). The system will happily tell your process that memory is available even when it's not, and relies on the OOM killer to free memory by force when necessary. The only context in which an application can reliably detect OOM is when that application is the kernel itself. Fortunately, Rust has a stripped-down version of the standard library, called libcore, that exposes features which don't require allocation and thus don't have to worry about OOM. This profile is perfectly usable for writing kernels, and could also be used to write an alternate kernel-specific stdlib which make it possible to handle OOM. > Complaining about the existence of Parse is like > complaining about the existence of unwrap in Rust. This is mistaken. Complaining about Parse would only be like complaining about unwrap if unwrap were the implicit and default behavior. Parse throws implicitly, but unwrap doesn't get called implicitly. The fact that the possibility is impossible to accidentally overlook is an enormous and crucial difference.
- deleted 11y ago[deleted]
- wvenable 11y agoI started to think about everything that's wrong with the authors code example and the more I got into it the more I realized the entire problem is wrong. "Our goal is to write a function that takes a list of previously released versions and a user-provided version string, which then returns the parsed number or reports an error." A function named CheckNextVersion should never even raise an exception because it expects bad input. It probably also shouldn't double up as the ParseNextVersion function as well. But I understand the author wanting to combine these operations and conveniently get an error message out that can be displayed to the user. But as a damning example of exception handling, it's just bad design. So even if we accept the design, his method is horribly over-thought with regards to error handling. Either it should catch within it's body all potential exceptions and raise a single InvalidVersionException or it should catch nothing and the code above should catch everything and display the message to the user. All the work catching and rethrowing different exception types adds no value given the purpose of the method.
- charlieflowers 11y agoI'd love it if some Rust insiders could comment on how Rust might implement the stack trace feature (assuming they did decide to implement it). Perhaps a trait such as "GeneratesStacktrace" that can be implemented with "Derives"? And the stack trace is only available in a Debug build when you compile with the appropriate flags?
- kibwen 11y agoI've barely given it any thought, but one approach would just be to modify the try! macro to dump a backtrace to stderr when an Err is encountered in debug mode. The backtrace itself could be generated the same way that they're generated for C++.