by flohofwoe · 3y ago · 0 comments
If anything, the latest round of systems programming languages which all use error unions instead of exceptions have demonstrated quite clearly that exceptions are actually quite pointless.
I suppose there's a window where you can't tolerate GC pauses but can have exceptions allocating memory unpredictably, but it's a pretty small window.
Exceptions are for exceptional situations, so the performance impact of them when thrown is rarely of concern - both in C++ and in pretty much every other language with exceptions. There's a reason something like Java still uses error return values for an awful lot of things, after all. But importantly exceptions means that you're not doing return value checking for errors that rarely happen, which can get expensive on the whole. As in, exceptions gives your code a path to both be cleaner and faster on average - they are really very useful when implemented well.
The problem with C++ exceptions has nothing to do with the memory allocation cost when thrown (which as mentioned, there's other strategies you can deploy than the default of just `new`). Rather it comes from the significant impact on binary size and the reliance on RTTI.
I'm not sure RTTI for exceptions is such a big deal.
I'm guessing you are referring instead to the the fact that exception catching needs pull in most of the dynamic casting machinery in many cases, since exception hierarchies at least in theory can have multiple inheritance, virtual inheritance, and other complications, which means that not only is determining if a specific exception thrown is compatible with a given catch clause non-trivial at runtime, but even once determined, the cast may be non-trivial, not to mention the possibility of catching by value needing to invoke a copy constructor.
If a language catches by type, some form of run time type indication in the exception object is fundamentally needed if the language allows throwing an exception whose concrete type is not known at initial throw time. C++ is such a language, as you can throw an exception that was allocated elsewhere, and which you received via a pointer to a non-final class.
In a language where the concrete type is always known at initial exception throw time, then the stack unwinding code could conceptually simply identify any catch blocks that would apply from data in the exception tables because all superclasses are statically known. And it could pregenerate code for any possible upcasting or copy construction needed, so no dynamic casting machinery would be needed.
(But many other static languages with exceptions only allow single inheritance, don't allow catching by interface, and only allow catching by reference, so no fancy copying or upcasting code is needed. Almost all of them do allow throwing without knowing the concrete type, so they need some form of RTTI data nevertheless.)
Edit: Also, depending on how they're used, exceptions can be easier to avoid than GC. IOW, if an exception has been thrown at all, you may well have bigger problems than the latency cost of throwing.
Go and Rust's panic is for unrecoverable errors. They both have the ability to catch panics because sometimes you really need to do that (e.g. when interacting with FFI or sometimes multithreaded code).
They are not exceptions though. I've seen this myth repeated a few times lately (always about Go and not Rust for some reason) and I wish it would die.
You wouldn't say C "has exceptions" would you?
Maybe that's just me, but I wish more people would say that C "has exceptions", if only because longjmp/setjmp[0] interacts with exception systems of other languages, sometimes badly.
That being said, I think an important difference is that in C setjmp/longjmp do not "unwind" objects, due to the lack of destructors.
However panics at least in Rust are just exceptions by another name. The difference solely comes from culture. Even the fact that unwind can be turned to abort is not significant, considering that pretty much all production implementations of C++ have fno-exceptions
[0]: https://learn.microsoft.com/en-us/cpp/cpp/using-setjmp-longj...
I don't think that is a requirement of exceptions. It's just a sensible thing that most implementations do.
> The difference solely comes from culture.
Maybe, but that is a huge difference! You can implement anything in any Turing complete language but you wouldn't say that they all "have" every feature...
To quote https://doc.rust-lang.org/std/panic/fn.catch_unwind.html :
> It is *not* recommended to use this function for a general try/catch mechanism. The Result type is more appropriate to use for functions that can fail on a regular basis. Additionally, this function is not guaranteed to catch all panics, see the “Notes” section below.
What they have actually shown is that error unions are not a panacea and a pain to handle manually. And that hardcore killing your app in the presence of even the tiniest of unhandled errors isn't suitable for any programming, especially systems programming.
That's why Rust ended up introducing try!, ? and catching panics. Go also added panic recovery.
- unions are not a panacea and are a pain to handle manually, as you wrote;
- but with a little syntactic sugar, they turn out to work really, really well, much better than C++-style exceptions.
There's something to be said for OCaml-style exceptions, which are actually even closer to zero-cost, but I wouldn't call OCaml a systems programming language.
Writing this as one of the persons who advocated for try! around the time of Rust 0.4 :)
(I.e. it's quite different from what was done with "async fn" support, where the Future return type is hidden via the 'async' specifier and the control flow is totally changed.)
Indeed. Because manually handling those are a pain in the butt. So they made a shortcut. That still needs to be handled by someone up in the hierarchy. Exceptions in all but name.
> It's not even monad-like because
No one cares whether it's monads or not.
The result of the branch method on Try is ControlFlow<Self::Residual, Self::Output>
Try isn't stable, but ControlFlow is. They've reified the control flow! Rust has a type which represents the idea of a decision whether to return early. This is in my opinion pure genius, and it happened almost by accident. It seemed natural at first that the decision to return early is manifested directly in Result, but it isn't. That's the insight. Failure and returning early are distinct ideas, and we might just as easily want to return early in consequence of success as failure.
In separating "Success versus Failure" from "Return early versus keep going" Rust gets a lot more value here than is encapsulated in C++ Exceptions.
But with added space and branch-predictor overhead in every call site, and runtime overhead in every call event!
In particular, checked exceptions.
This is a very interesting article that discusses the isomorphism between checked exceptions and error return types, they ended up with checked exceptions where a function Foo that may throw must be invoked with "try Foo()" - very similar to Rust's ADT-based macro/syntax.
If anything it enables the enforcement of strong invariants and leads to better and safer code.
There's lots about exceptions which is inappropriate for system programming, starting from FFI unsafety and the lack of signaling to callers (which makes resilient use more difficult).
> If anything it enables the enforcement of strong invariants
It doesn't do that.
> and leads to better and safer code.
It only does that in comparison to truly deficient (e.g. c-style) error reporting, and that's being generous.
The alternative that the parent said was making all of your state be a union with some kind of error, and making sure all accesses handle the fact the variable might be in a erroneous state. That is a huge explosion of possible states in your program, and essentially making every invariant weak everywhere.
Then FFI, I suppose you mean interfacing with C. Problems that arise when interfacing with other programming languages are orthogonal to a language's ability to be used for system programming. Obviously you wouldn't let an exception propagate through some C code, that's forbidden.
Error sum types do the exact same thing.
> The alternative that the parent said was making all of your state be a union with some kind of error, and making sure all accesses handle the fact the variable might be in a erroneous state.
Which is a non-issue as it is lifted to the type system. The type system will not let you forget about that.
> That is a huge explosion of possible states in your program, and essentially making every invariant weak everywhere.
You get an error state added to a given value, which you also get via exceptions, except implicitly and without notification of the additional state.
Type-safe error values also provide simpler error handling and recovery in many case, because they don't require split-path handling.
> Then FFI, I suppose you mean interfacing with C. Problems that arise when interfacing with other programming languages are orthogonal to a language's ability to be used for system programming.
It very much isn't, part of the system programming workload is to provide reusable components.
> Obviously you wouldn't let an exception propagate through some C code, that's forbidden.
And rarely if every checkable statically, hence unsafe.
EPIPE
Erroneous states can arise outside of your control at any time.
Not letting exceptions escape at API boundaries has been a technique for a few decades. It’s not rocket science.
Writing exception-safe code is likewise an ancient technique by now. Meyers’ books which explained such things were published in the 90s…
It's not signalling which has been shown to be a complete mistake, but checked exceptions, more specifically as implemented by Java.
Signalling works just fine and is actually rather enjoyable when done well.
Because the only way it is not ever a maintenance nightmare is when you really don't care that function execution could be aborted at any point without any visual clue. And the only way I can see you wouldn't care is when you go 100% in to everything-context managed / RAII or similar. And that again, sorry but I can't be arsed to prematurely rip everything into little pieces like that. It makes for terrible code IMO.
My experience has been the opposite. Ensuring exception safety in a type that has nontrivial move/copy operators (that is, a type that for whatever reason can’t follow the “rule of zero”) is often a research-level problem. Not having to worry about that in Rust is such a breath of fresh air.
Exceptions do exist in Rust, and you do need to catch it explicitly at the FFI boundary. [1][2] And the programmer needs to take care their abstractions are safe with stack unwinding when writing any kind of unsafe code in Rust. (For an example: [3])
[1] https://doc.rust-lang.org/nomicon/unwinding.html
[2] https://doc.rust-lang.org/std/panic/fn.catch_unwind.html
Enforcing strong exception safety might require some thought, but it's definitely not "a research-level problem".
In any case either of these is miles easier than satisfying the Rust borrow checker, unless you use the cop-out of (A)rc.
Regardless, how the invariants of your objects are maintained in case of operation failure is something you should be thinking of regardless of the language.
That's not my experience as a C++ developer in a complex, cross-platform, application, which needs to:
1. interact with C;
2. operate with an event loop;
3. operate/interact with a GC;
4. interact with non-trivial system libraries (e.g. Direct3D, Vulkan, ...)
> In any case either of these is miles easier than satisfying the Rust borrow checker, unless you use the cop-out of (A)rc.
The borrow checker is indeed complicated. I'm not sure how you define "satisfying", though. As for (A)rc, it can definitely be interpreted as a "cop-out" or as delaying optimization until you actually have good reasons to believe that you need it.
How?? If a container have `get(K)->V` and `remove(K)->V` then how does it preserve this invariant? This is an impossible contract to satisfy once you try to push once and pop twice. The container is promising you something that it can't satisfy, I would rather have a container that's honest with `get(key)->Maybe(value)`.
We've used exactly for this reason to improve performance, albeit this was a long time ago.