7 ms·
Working with and implementing C++ exceptions for 30 years now, including implementing exception handling for Windows, DOS extenders, and Posix (all very differe
by WalterBright 5y ago
Working with and implementing C++ exceptions for 30 years now, including implementing exception handling for Windows, DOS extenders, and Posix (all very different), and then re-implementing them for D, I have sadly come to the conclusion that exceptions are a giant mistake.
1. they are very hard to understand all the way down
2. they are largely undocumented in how they're implemented
3. they are slow when thrown
4. they are slow when not thrown
5. it is hard to write exception-safe code
6. very few understand how to write exception-safe code
7. there is no such thing as zero-cost exception handling
8. optimizers just give up trying to do flow analysis in try-exception blocks
9. consider double-fault exceptions - there's something that shows how rotten it is
10. has anyone yet found a legitimate use for throwing an `int`?
I have quit using exceptions in my own code, making everything 'nothrow'. I regret propagating exception handling into D. Constructors that may throw are an abomination. Destructors that throw are even worse.
- tux3 5y agoWhat do you think of languages that use sum types for error handling, but can still unwind in a few scenarios? Reasonnable compromise, or should we get rid of all unwinding always? And if so, do we abort() or do we ask users to handle any and all possible errors.
- WalterBright 5y agoI've read the proposals for it. It certainly looks good, yet exception handling looked good 30 years ago, too. I haven't used sum types myself, and often it takes years to discern whether things are really good ideas or not. What I personally use is the "poisoning" technique. This involves marking an object as being in an error state, much like a floating point value can be in a NaN state. Any operation on a poisoned object produces another poisoned object, until eventually this is dealt with at some point in the program. I've had satisfactory success with this technique. It does have a lot of parallels with the sum type method.
- winstonewert 5y agoSo that sounds like the way invalid floating point operations give NaN, and then the NaN propagates everywhere. I've always found this super annoying because its often hard to figure out where the NaN comes from. Does your solution differ from this in a way that's less annoying?
- WalterBright 5y agoThe FPU does not include the source in the NaN, but that doesn't mean your own objects can't. What I do is have the error reported at the source, and then return the poisoned object. A better way would possibly be put the error message in the poisoned object, and report the error somewhere up the call stack.
- erik_seaberg 5y agoWhat are the return values from a poisoned object’s methods? Does a poisoned vector have a poisoned integer as its size?
- WalterBright 5y ago> What are the return values from a poisoned object’s methods? That's up to you. You can do it as: 1. return a poisoned value 2. return a safe value, like `0` for its size 3. treat it as a programming bug, and assert fail 4. I know `null` is hated, but it is the ultimate poisoned value. Try to call a method on it, and you are rewarded with a seg fault, which can be considered an assert fail. 5. design your poisoned object to be a real object, with working methods and all. It can be the same as the object's default initialized state. In other words, it's necessary to think about what the poisoned state means for your use case. I use all those methods as appropriate.
- Gibbon1 5y agoI do that a lot with the firmware I write in C. typedef struct { err_t error; int error_line; char *error_msg; ... ... } thing_t; // set out of range error thing->error = THING_ERROR_OOR; thing->error_line = __LINE__; thing->error_msg = "outofrange" You can grep on 'outofrange' and find where the error was set. I originally started doing that to mark 'bad' analog readings in process control equipment. I wrote my filters and control loops to be able to 'eat' occasional bad readings without barfing. Worked very well.
- mbrubeck 5y agoRust is one such language. I wrote a bit about exception safety in Rust here: https://users.rust-lang.org/t/c-pitfalls-hard-to-avoid-that-are-elegantly-managed-in-rust/38006/16 https://users.rust-lang.org/t/c-pitfalls-hard-to-avoid-that-... In short, while the problem is mitigated somewhat compared to C++, it's still one of the most common causes of bugs in unsafe Rust code. Rust programs can choose to abort on all panics, rather than unwind. Firefox does this, for example.
- volta83 5y agoWe do this on all our Rust code as well (1.1 million LOC at this point). While we can benefit from #[no_std] crates on crates.io, unfortunately we can't use any crates that require standard because the standard library does not propagate errors properly, so we maintain our own implementation of most of the standard library for Linux only, that propagates all errors using Result.. It's a huge pain point, but at least Rust allows us to do it.
- oconnor663 5y ago> does not propagate errors properly Is "panicking on allocation failure" the only example of this, or are there others?
- AndyKelley 5y agoNow that I've been using Zig's error handling language primitives for some time, I've come to realize what the paradigm really is: a way to encode a "forwards" and a "backwards" at the same time, for the same block of code. The usual way control flow progresses is forwards, but when an error occurs, it goes backwards, over the defers and errdefers. C++ exception handling and other languages with destructors force you to do this declaratively, but then don't give enough control over exactly the situations they matter in: setup and teardown. Meanwhile with explicit control, you just encode exactly what happens in the "backwards" control flow. No surprises, no trying to figure out what happens based on declarative rules. Once I figured this out, I was able to use it to simplify the logic of some things in the self-hosted compiler that are extremely error prone in the C++ implementation: * Lazy source locations: passing in "none" for a source location, and then handling the "error.SourceLocationNeeded" and then doing the expensive calculations to find the source locations before retrying the operation. * Generic instantiations: returning "error.GenericPoison" for when a type parameter cannot be determined without information from the callsite. In this case, the analysis is cleanly aborted and function marked as generic. I'm pleased with how this turned out, and I've started to think of other languages in terms of how they map to this "forwards" and "backwards" control flow concept.
- neeeeees 5y ago> they are slow when not thrown I thought the not-thrown case was pretty much zero-cost, at least in newer versions of Clang... How much of a slow down are we talking here?
- WalterBright 5y agoThe main reason is the optimizer abandons trying to figure out flow-of-control when half the expressions can throw and present a path to the catch blocks. Furthermore, this all inhibits en-registering variables, because exception unwinding doesn't restore registers. If you want your code to be fast, use 'nothrow' everywhere. I don't know about newer versions of Clang, but I recall Chandler Carruth mentioning that LLVM abandons much optimization across EH blocks as infeasible.
- titzer 5y agoJava JITs are considerably more advanced than this. It's expensive to put in all the additional control flow edges to model exceptions, but once done, control and data flow analyses just work, as well as loop optimizations, code motion, inlining, register allocation--all of it "just works" (TM). Then you have to spit out a metric crapton of metadata to allow searching for the correct handler at runtime, but that's the slow path. All of that is to say that Java try blocks do not have any direct dynamic cost when exceptions are not thrown. Even throwing exceptions and catching them locally in Java can be fast. If everything gets inlined into one compilation unit and the exception object is escape analyzed, HotSpot will absolutely just emit a jump. Not that I disagree with your overall point--Virgil just doesn't have exceptions--but from your description here it just sounds like your compiler is far behind the state of the art in terms of optimizing exception-heavy code.
- WalterBright 5y agoJava has a far, far more restricted view of exceptions than C++ and D have,[1] and hence more opportunities for optimization. I did implement exceptions in the Javascript compiler I implemented 20 years ago, and they're a cakewalk compared to C++. I also implemented a native Java compiler, including EH. As for clang, see what Chandler said. But maybe things have changed in the last couple years. [1] for example, Java doesn't have objects on the stack that need their destructors run. That's a massive simplification.
- WalterBright 5y agoAt least with D a thrown exception must be a subtype of `Throwable`. I.e. you can't throw an `int`, oh, and the incredibly confusing throwing of an object that itself can throw.
- WalterBright 5y agoP.S. I implemented Structured Exception Handling for Win32, with help from a couple very smart people. Microsoft completely changed it for Win64, and the documentation on it is completely unhelpful to nonexistent.[1] I simply gave up on it. D on Win64 uses the exception handling mechanism I invented for the 32 bit DOS extender from the old Zortech days. It works fine, except that it cannot interact with C++ exceptions thrown by VC++ code. [1] I attended a presentation on it by MS soon after Win64 came out. All I could think of at the end was "what's a cubit". I understood exactly nothing about it.
- Iwan-Zotow 5y agoAh, Zortech C++. That indeed brings back some memories. Walter, what do you think about Herb Sutter "new" C++ exceptions (which is basically about throwing an int/a word) ?
- WalterBright 5y agoIf there's anyone who can think of a better way, it's Herb. I'd take anything he has to say about C++ very very seriously.
- deleted 5y ago[deleted]
- daenz 5y agoCan you describe your ideal error handling mechanisms? Or at least other mechanisms that feel more correct?
- WalterBright 5y agoI'm not going to recommend any technique I don't personally have years of experience with. Too many times a paper that makes something look great tends to have fatal flaws that only emerge years later. Sort of like WW1 strategies that sounded good but in practice produced only mud and dead bodies. As I mentioned in another comment, I've had good success in the trenches with the poisoning technique.
- gHosts 5y agoI would go with the Erlang approach. Just die FFS. Let the process monitor restart you if you deserve to live.
- TeMPOraL 5y agoThat only makes sense if units of your code run in a loop and communicate asynchronously :). But, if you want a simple supervisor pattern in C++, then... try/catch block is your supervisor, exceptions are how your process dies. Consider: template<typename Fn> auto CallWithSupervision(Fn fn) -> decltype(fn()) { // supervision loop // configure conditions as needed while(true) { try { return fn(); } catch(std::exception& e) { // log failure details } catch(...) { // optional: exceptions out of handled set? // kill supervisor. throw; } } } //elsewhere CallWithSupervision([relevant=state,&nd=captures]() { return Client(relevant, nd); }); Modify as you see fit. It's the simplest, synchronous Erlang supervisor, in C++. And it will already work with your code - exception handling is very composable this way.
- gHosts 5y agoExcept it isn't robust. Exceptions occur when "Very Bad No Good Undefined Horrible Things" have (at last, been found to have) happened. So if you have no guarantee that the memory space is uncorrupted, you have no guarantee that all resources have been recovered, you have no guarantee that in attempting to deallocated resources that they have been allocated in the first place. (Read the fine fine print on exceptions in constructors and destructors.) TL;DR; Don't do that. But exceptions are what happen when people do what they shouldn't.
- otabdeveloper4 5y agoForcing the programmer to manually write stack unwinding code is not a solution. That's like saying "garbage collecton is slow and complex, just use malloc() and free() instead".
- jstimpfle 5y agoNobody said to manually write stack unwinding code or to only use malloc() and pair each of them with free(). There are other very good solutions that involve explicit structure. For example - do not free things at all, just reserve a big chunk of address space and let the OS populate it as needed. When the process quits the OS frees everything automatically. - do the same thing for parts of the program but implement the "OS part" in the program itself. There are variations of this known by terms such as "memory arena" or "pools". Basically, just take care to group allocations by end of lifetime. Then you can free everything in one go without tracking each lifetime individually in a stack frame (which is insane).
- grandinj 5y agoOn the other hand () they solve a handful of use-cases really really well. () if you are writing relatively decent C++, most code is pretty much exception safe already () lots of abstractions are dangerous when mis-used () they are sufficiently low cost that they almost never show up in the fairly extensive perf profiling I do on a large real-world application (LibreOffice). And LibreOffice throws exceptions __a lot__ (*) Except for toolchain writers, nobody cares how they are implemented
- tialaramex 5y ago> LibreOffice throws exceptions __a lot__ They're terrible for this. C++ Exceptions are a perfectly good exception mechanism, but what C++ programmers are trained to do with them isn't exceptions but error handling and they're not suitable for that. "I tried to create the file but it already existed" is an error - and now you're going to write the unhappy path code, this is the wrong place to have exceptions. "I tried to create the file but the OS now says the abstract concept of files is alien to it" is an exception. You are not prepared for this eventuality, the best you can do is explain to the user as best possible what happened and hope a human knows what to do.
- grandinj 5y agoI guess people's experiences are different :-) I find exceptions to be a perfectly fine error handling mechanism. I certainly prefer it to cluttering my code with explicit checks for return codes and such like.
- dnautics 5y agoreturning errors doesn't have to have cluttered code. Just because Go messed it up doesn't mean it's bad.
- TeMPOraL 5y ago> error handling and [exceptions are] not suitable for that I disagree :). Exceptions are fundamentally equivalent to "return sum type" error handling pattern. In an exception-enabled environment, you can imagine every function returning some Foo is really returning a {Foo, Error}. Then, every call like below, outside of try/catch block: value = SomeFunction(); is secretly translated to: maybeValue = SomeFunction(); if(!maybeValue) { return maybeValue.error(); } You can devise analogous translations for code in try/catch blocks. The fundamental difference between exceptions and an Expected/Maybe mechanism is that exceptions don't force you to be explicit about all those Maybe values. If you want to handle some Error three layers up in the call stack, you don't have to litter the intermediary layers with explicit Maybes everywhere. (This is, unfortunately, also their drawback in typical implementations - the set of possible Error types in the hidden Maybes becomes effectively open-ended, when with explicit Maybes, it's constrained and visible in source code - and, perhaps more importantly, in the ABI.) The other day I did an experiment - I wrote two equivalent pieces of nontrivial production code, one using C++ exceptions, and other using the tl::expected library. If you looked past the syntactic noise, they mapped almost 1:1 in terms of error handling and error recovery patterns.
- dataflow 5y agoDon't you need exceptions though? How do you terminate arbitrary operations without exceptions? Like say you call an algorithm (like std::sort) and during a callback (e.g. in the comparator) you decide to cancel the operation (perhaps user-requested). With exceptions it's easy; you just throw an exception and then catch it. No need to touch or even know the intermediate callers. But without exceptions what do you do? You have to go modify or reimplement the source code of every intermediate function, which is a giant waste of effort at best, and in reality a likely vector for introducing code duplication, brittleness, and bugs.
- ilammy 5y agoBut with exceptions what do you do? You have to go modify or reimplement the source code of every intermediate function to be correct and safe when an exception is thrown at every point where it can be thrown, which is a giant waste of effort at best, and in reality a likely vector for introducing code duplication, brittleness, and bugs. The point is, retrofitting exceptions onto existing codebase is a lot of pain. Interruptible functions have the API they have because they have been designed with exceptions in mind for interruptions. If there were no exceptions, the callbacks would have had a different API. A special return value could be used to signal an interruption.
- dataflow 5y agoNo you don't, you're massively exaggerating. The standard library already has at least basic if not strong exception-safety all over it. And RAII is pretty darn standard practice and guarantees basic exception safety in your own code too. You don't need strong exception safety here, just basic is sufficient for most such cases. Go try this with std::sort (or std::adjacent_find or whatever) and tell me which of their implementations you had to modify.
- ilammy 5y agoWell but of course! These functions are already implemented with basic exception safety in mind. What if they weren't? This is exactly the same situation as a function that has callback(); which cannot be changed into if Err(error) = callback() { return error; } because that would break some invariants. Changing return type from "void" into some "result" is a mechanical change.
- cjfd 5y ago"has anyone yet found a legitimate use for throwing an `int`?" I could image throwing an int when writing a shell utility and throwing the return value of main as an int but I suppose doing that usefully would be pretty rare. Usually one cares more about whether a shell utility is successful or not not so much about the precise reason it failed. So, while I could imagine doing that, I don't see myself going for that option too likely.
- WalterBright 5y agoYes, but you couldn't mix that code with code that throws an `int` for other porpoises. It becomes a global straightjacket for your code.
- cjfd 5y agoYes that is true. One really should not start throwing integers in code that one hopes to reuse someplace else.
- stinos 5y agoI have quit using exceptions in my own code, making everything 'nothrow'. Assuming not all code you use is your own, how does this work in combination with other code (like the STL) which is not nothrow?
- WalterBright 5y agoGeneric code (like you'd find in a library) is usually done with templates. Templates in D infer `nothrow`, giving them the advantage of being implicitly `nothrow` when their arguments are also nothrow. Inferring attributes this way is a major way D works.
- stinos 5y agoAh, sorry, I was thinking you were talking about not using exceptions in C++ anymore.
- omegalulw 5y ago+1 plain old return error codes and the related modern status codes are the way to go. Lots of people say this is more work. I would your comment does a good job explaining why that work is immensely useful.
- josefx 5y ago> plain old return error codes and the related modern status codes are the way to go Why yes I just love to get a "Error one of the billion files this application tried to load wasn't available ErrorCode: ERR_MISSING_FILE_FUCK_WHO_KNOWS_WHICH". What I like about exceptions is that they make information that can't be encoded in a 32 bit integer value available to top level error handlers.
- saagarjha 5y ago> has anyone yet found a legitimate use for throwing an `int`? Not sure if you consider this legitimate, but I have seen code that throws an errno.
- blub 5y agoThose look like problems for compiler implementers (tiny subset of users) or those writing code with very tight performance requirements (large amount of C++ code does not have such reqs). In spite of the reasons given, exceptions are successfully used (in C++ too) for error handling, because they can be much nicer that shuffling error codes/result types up the stack. Really, as an end-user the issue with exceptions in C++ is another: a) it's impossible to figure out what throws by looking at code. b) it's (nearly) impossible to ensure that something doesn't throw This means on one hand that one has to assume that any code can throw and manage resources appropriately, which is by now known and there are well-established idioms around it. On the other hand though it also means that the silliest error from a tiny library can bubble up into the event loop/main function and terminate an application. Swift's syntax for exceptions illustrates what I mean, even though Swift does not unwind the stack.
- minipci1321 5y ago> 10. has anyone yet found a legitimate use for throwing an `int`? I use that a lot in constexpr computations -- to stop the compilation, I usually do 'throw __LINE__'. -- Using a more complex type is not warranted -- there is no catching end in constexpr. -- And in case the same routine ends up called non-constexpr, it will be easy to identify the place that called 'throw' -- line numbers are unique without additional effort. Just don't put two throws on the same line.
- WalterBright 5y agoThat works until you incorporate code that throws errno.
- jokoon 5y agoWho invented exceptions in the first place? Did they first appear in Java, encouraging C++ to imitate a java feature?
- josefx 5y agoSoftware wise it seems to originate from Lisp[1]. [1]https://en.wikipedia.org/wiki/Exception_handling#History https://en.wikipedia.org/wiki/Exception_handling#History
- Const-me 5y ago> 10. has anyone yet found a legitimate use for throwing an `int`? When an integer is the only value I need in the catch handler, I sometimes throw them, but only negative integers. https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/0642cb2f-2075-4469-918c-4441e69c548a https://docs.microsoft.com/en-us/openspecs/windows_protocols...
- freesoftware 5y agoI'd suggest to use Lisp, which is a under-rated yet powerful language. [Why?] https://gigamonkeys.com/book/introduction-why-lisp.html https://gigamonkeys.com/book/introduction-why-lisp.html [Exceptions] https://gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts.html https://gigamonkeys.com/book/beyond-exception-handling-condi...
- renox 5y agoThat's funny: I thought you were a proponent of exceptions because I read (a lot of years ago) a mail from you which said "who is going to check that printf failed"? And this remain true: a lot of things can fail (arithmetic operations, every IO, etc) so the error system must be very "lean" otherwise the "happy path" is drowned in the error propagatio/handling code..