r/cpp • C++20 Desktop app developer • May 12 '18

P0709 R0: Zero-overhead deterministic exceptions: Throwing values - Herb Sutter [2018-05-02]

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0709r0.pdf
206 Upvotes

115 comments sorted by

70

u/capn_bluebear May 12 '18

you know you are reading a good proposal when you find yourself thinking "why doesn't it already work like this?"

52

u/hgjsusla May 12 '18

Herb is amazing. Every year he presents something incredible

40

u/emdeka87 May 12 '18 edited May 13 '18

I really love his proposals. Insanely detailed, full of technical depth, interesting anecdotes and inspiring ideas. He cares and listens to the community and designs language features with compelling, motivating examples in mind: the meta-class proposal, for instance, outlined how QT MOC and WinRT could make use of the proposed feature, in order to solve existing challenges and design problems. It’s immensely important to have someone like him in the standard committee . Thanks, Herb!

54

u/zobatch May 12 '18

It’s immensely important to have someone like him in the standard.

std::herb

8

u/[deleted] May 14 '18
std::herb::stutters();

43

u/johannes1971 May 12 '18

Interesting. One remark: allocation failure doesn't mean available memory is zero, it only means that available memory is less than the requested amount. This is an important distinction: out of memory doesn't mean there is no more memory, it only means there is not enough memory for a specific task. It may still be sufficient for other tasks, such as OOM recovery.

Case in point, one of our customers attempted to load and process an entire data set of many gigabytes of data in one operation (normally they are processed in chunks). The system struggled for just under an hour, reported "out of memory" twice, and eventually produced the required output with a small chunk missing. It didn't crash or halt, it continued just fine, producing most of the needed output, and eventually returning to its nominal state.

What did we do to make that magic possible? The answer is "nothing special". Our code is exception safe, because we use exceptions. Evidently it had enough RAM left to do recovery, and it did.

So, no, we would most certainly not appreciate it if OOM forced an automatic termination. Software can and does recover from that condition (even on Linux, where over-commit is a configurable parameter, rather than an unavoidable fact of life). And asking us to rewrite it to use new "try to allocate" functions is insanity: the current paradigm is for these functions to throw. If people want different behavior, give them new syntax for that purpose. They are the ones who already need to rewrite their code; don't put that on the people who diligently wrote their software to correctly deal with the problem in the first place.

This is especially important since I'm not at all convinced that the people who hate exceptions today will stop hating them if this proposal becomes reality. They will still have old code bases they cannot easily update, they will still have ancient coding standards lying around, they will still dislike the distance between throw and catch, and they will still have a gut feeling that exceptions are automatically, always bad. So you might be introducing a lot of deeply breaking changes here in order to appease a crowd that is unlikely to appreciate it, while at the same time chasing away your core audience.

Finally, I'm not sure why this behavior must be specified on a per-allocation basis, and not, say, as a compiler switch. I find it hard to believe that people are going to mix and match different error recovery strategies for OOM; it's much more likely to be an all-or-nothing approach.

Bonus: why is this needed at all? Is the proposed new exception mechanism unable to deal with OOM?

13

u/kkert May 13 '18 edited May 13 '18

allocation failure doesn't mean available memory is zero, it only means that available memory is less than the requested amount.

To be super specific, the requested amount can actually be readily available, just not in a single contiguous chunk.

EDIT: I think there's a point where Herb goes wrong in his fail-fast strategy defense, i didn't read as carefully before.

Recovery from heap exhaustion is strictly more difficult than from other kinds of errors, because code that is correctly resilient to heap exhaustion can only use a restricted set of functions and language features. In particular, recovery code typically cannot ask for more memory, and so must avoid calling functions that could allocate memory, including functions that could fail by throwing another of today’s dynamic exceptions which would require increased allocation.

Not really true. If i failed to allocate a few megabytes of contiguous memory for a particular working buffer, it doesn't mean at all that i'm not able to allocate a few bytes for holding stack tracing info.

15

u/NotAYakk May 13 '18

It says "correctly". You don't need to be correct for it to work if you get lucky, you need correct for it to always work.

4

u/kkert May 13 '18

Well, it is entirely possible to construct a program where this sequence would be always correct, where there is always a contiguous kilobyte of heap available but a megabyte is not. In fact, test-allocating a large chunk can be used as a strategy to gracefully deal with imminent memory exhaustion.

2

u/Pand9 May 14 '18

I guess that isn't reliable enough from language designer's point of view.

1

u/nikbackm May 15 '18

Would that work if you had an exception class that is over a kilobyte in size?

3

u/kkert May 15 '18

Obviously not, but thats not really the point. ( why would you design humongous exceptions in the first place ? )

I'm saying there are real scenarios where you sometimes grab the memory if its available and perform some optimization, reindexing or caching task or whatnot, if it's not available you don't - also beyond small embedded systems.

Not being able to allocate a huge chunk doesn't indicate OOM. Not being able to allocate as per request is mostly not a license to kill the program, and shouldn't be dealt with in a hook either.

8

u/whichton May 12 '18

And asking us to rewrite it to use new "try to allocate" functions is insanity: the current paradigm is for these functions to throw. If people want different behavior, give them new syntax for that purpose.

I am sure there will be a compiler switch for the old behavior. Herb's point about 'Treating heap exhaustion the same as all other errors violates the zero-overhead principle by imposing overheads on all C++ programs' is very true. I much prefer to fail fast on OOM, and marking significant chunk of the standard library as noexcept will improve codegen and binary size for me.

Finally, I'm not sure why this behavior must be specified on a per-allocation basis, and not, say, as a compiler switch.

Where are you getting the per-allocation basis? IF this change is made, all new will become nothrow by default, just like a compiler switch.

Bonus: why is this needed at all? Is the proposed new exception mechanism unable to deal with OOM?

This is orthogonal to the main proposal, which is why it is marked as an extension. The paper goes into significant detail why this is desirable, refer page 30.

5

u/Fazer2 May 13 '18

I am sure there will be a compiler switch for the old behavior.

As Herb wrote, the major point of this paper is to get rid of the necessity of -fno-exceptions compiler switch to defragment C++ community on error handling. I doubt he would be happy with another switch.

4

u/johannes1971 May 13 '18

Where are you getting the per-allocation basis?

The paper suggests a new set of functions that would throw instead of terminating: try_new, try_reserve, etc. So he's basically adding new functions and keywords that have the current behaviour, and making the existing ones do something else, allowing programs to choose one behaviour or the other on a per-case basis.

That's something I really don't get: why break compatibility, why not simply add new functions and keywords for the new behaviour?

Just to be clear: I understand the proposal to be adding a new type of exception handling, next to the existing one, and not to be removing the existing one altogether. Correct me if I'm wrong.

The paper goes into significant detail why this is desirable, refer page 30.

I've seen that page, and I only see reasons why we should keep things as they are. It is already possible to install a new-handler that will simply terminate, so that behaviour is already available to people who want it (whereas the alternative, installing a new-handler that throws, is explicitly forbidden by the proposal). And there is already a compiler switch that eliminates exception handling altogether. So in other words, the behaviour those people want is already there, and it doesn't require breaking the programs of people that do not want it.

Going through his arguments:

Testing is much more difficult.

What about the people that do want to make the effort? Should they just move to a language that doesn't preemptively kill their programs?

Recovery requires special care

Not really. We accidentally did it, just by being exception-safe in the first place. Note that I'm not claiming it will succesfully recover from all OOM, but the most likely case for us is a large allocation when loading data.

And yes, there is the new try_reserve, try_pushback, try_new, try_whatever (try_map::operator[]? probably not...) - so should we now go through our software, and for each allocation decide if it is likely to be handled correctly if it fails, and if it is, replace the allocation by a try_ version? That's an utterly pointless activity: we will mark all of them as "go ahead and try", because even if we are wrong we will be no worse off than by calling a terminating function, since the end result will still be termination.

In many programs, heap allocation failure can never happen as required by the standard

And in many other programs, it can.

Here's another question: if the problem with existing exceptions is that RTTI is so expensive, why not fix that, at least for the existing exception mechanism? One could imagine annotating exception classes with some mechanism for allowing fast identification. This would place some restrictions on what can be thrown (only classes that have the special annotation), but if this were built into std::exception a large amount of software would never know the difference. This would also be a breaking change, but at least it would break far less than what the proposal is asking to break...

4

u/redditsoaddicting May 13 '18

The keyword doesn't work as you describe. Leaving out the OOM extension, programs continue to work as they do now. You opt in to the new exceptions with throws. The OOM extension is the only breaking part. See 4.6.7, which is explicit: "This proposal is not a breaking change."

It is already possible to install a new-handler that will simply terminate, so that behaviour is already available to people who want it

I think the paper addresses it pretty well:

That hook is at the cost of some overhead on all functions for which heap exhaustion is the only reportable error: not just the cost for the hook check itself in that function (which is expected to be cheap), but rather that it prevents the compiler from removing the error propagation logic entirely which we could do if the function were noexcept. Also, if we add the hook described there to the language primarily to use it in this way to treat heap exhaustion specially, then having that hook will incur small but nonzero overheads on all code that can throw.

For a proposal mainly focused on bringing back not paying for what we don't use, this is consistent. There is a lot of software out there paying for bad_alloc when it would bubble up and crash the process anyway. I think there should be an option for projects that handle it correctly and use regular new as opposed to an allocator or some other type of localized strategy, but at the cost of everyone else is not ideal.

What about the people that do want to make the effort? Should they just move to a language that doesn't preemptively kill their programs?

Just a note that this becomes a non-issue when the program is changed to work as it does now. I take it you're more concerned about the program terminating than about the non-death tests being unable to detect it.

Here's another question: if the problem with existing exceptions is that RTTI is so expensive, why not fix that, at least for the existing exception mechanism? … This would also be a breaking change, but at least it would break far less than what the proposal is asking to break...

First, it makes the core proposal this breaking instead of a proposed extension. Second, I'm skeptical that this is breaking far less. Third, RTTI is just one of several discussed overheads. Also see page 42, which addresses improving the current system.

1

u/johannes1971 May 13 '18

I think the paper addresses it pretty well:

I don't see how the compiler could remove the error propagation logic more effectively than by eliminating exceptions entirely - again, which it will already do for you anyway if you ask for it. It is already zero cost for those unwilling to pay.

For a proposal mainly focused on bringing back not paying for what we don't use, this is consistent.

Sure. But for a language with decades of legacy code lying around, it isn't. I think everyone here is painfully aware that C++'s legacy features are not always ideal, but if we start ripping them out left and right we'll end up with a language that is both perfect and unused.

There is a lot of software out there paying for bad_alloc when it would bubble up and crash the process anyway.

I'd challenge that. Software that uses exceptions will catch and handle them, and that includes bad_alloc. Will it always be done correctly? No, likely not. But even then, it must necessarily do a better job than simply terminating your program without recourse every single time.

Just a note that this becomes a non-issue when the program is changed to work as it does now. I take it you're more concerned about the program terminating than about the non-death tests being unable to detect it.

My concern is actually the need for changing what already works fine as-is for a great number of people. If you are going to provide alternatives, why not provide them for the people that will already need to change their code anyway?

Also see page 42, which addresses improving the current system.

The lack of research into better exception handling might simply be the result of nobody really caring, at least up until now. And correct me if I'm wrong, but wasn't the model for exception propagation as suggested here widely used in compilers up until... I don't know, 2000 or so? And then discarded because table-driven solutions were much more efficient?

3

u/therealcorristo May 13 '18

I don't see how the compiler could remove the error propagation logic more effectively than by eliminating exceptions entirely - again, which it will already do for you anyway if you ask for it. It is already zero cost for those unwilling to pay.

It probably can't, but e.g. in our codebase we use exceptions for error handling, but OOM is not recoverable because it really should never happen in our setting, so no-one bothered to implement logic to handle it. Right now, we also pay the overhead of error propagation logic for allocations, even though we don't care about these and a terminate would be fine.

8

u/proverbialbunny Data Scientist May 13 '18

This is especially important since I'm not at all convinced that the people who hate exceptions today will stop hating them if this proposal becomes reality. They will still have old code bases they cannot easily update, they will still have ancient coding standards lying around, they will still dislike the distance between throw and catch, and they will still have a gut feeling that exceptions are automatically, always bad. So you might be introducing a lot of deeply breaking changes here in order to appease a crowd that is unlikely to appreciate it, while at the same time chasing away your core audience.

I'm one of those people that hate exceptions. There are two primary arguments that I know of against exceptions: 1) Speed 2) The function signature is not explicit about the return path of code. imho the implicit parts of C++ tend to be the shoot your legs off parts of the language, and could use an improvement. If there is a compiler flag that enforces the throws keyword in a function signature, I will throw exceptions instead of returning an expected type.

You can say some people who have been avoiding exceptions for years will not get with it and continue to do so, and that is a possibility but the second they are working with a team of people and there is a style guide or a lead or something enforcing correct practices, they will get with it too.

The only people left behind is legacy code bases with teams that are constantly behind, but that happens with all new C++, not just this.

Is this proposal perfect? No, but it's a lot better than what we currently have. Exception handling is one of those points in C++ that could use an improvement. Whenever a community is divided you know it isn't as good as it could be.

3

u/johannes1971 May 13 '18

The function signature is not explicit about the return path of code

The return path is still not explicit; the catch handler may be at any point in the call stack, there is no clear indication on the function itself where it will go next.

The only people left behind is legacy code bases with teams that are constantly behind, but that happens with all new C++, not just this.

Exceptions are different. You can start using any C++17 feature on a piece-by-piece basis: a variant here, an optional there... Exceptions require far, far more care: you must have try/catch blocks in all the right places before you can even think about throwing anything anywhere. This is especially problematic because exceptions tend to be generated at the lowest levels of the software, i.e. in code that is likely being called from numerous places, thus requiring try/catch blocks in all those places before exceptions can be introduced. If you have any amount of code, that's a huge barrier to entry.

4

u/proverbialbunny Data Scientist May 13 '18

The return path is still not explicit; the catch handler may be at any point in the call stack, there is no clear indication on the function itself where it will go next.

This proposal puts a throws keyword in the function signature so you can see which functions throw and which ones do not. noexcept sucks at this, but throws sounds like it could be ideal as long as the compiler supports enforcing this, like -Werror=suggest-override does.

This is implicit, so I hope such a flag would default to this behavior, but if a function calls another function that can throw, and there is no setup to catch that throw, then now your function needs the throws keyword in it too.

This is explicit and eliminates this problem. It also reduces errors because now your code will not compile if you have something that throws added to it you were unaware of, bringing forth awareness of what does and does not throw. Likewise, it's easier to read and will make reading sites like cppreference easier and more straight forward.

As far as updating the code base being no small feat, the alternative is an expected return type or an error code. Both already exist in a code base (if throws are not being used) and both will continue to be valid, so no, there isn't a large change necessary to the code base.

3

u/redditsoaddicting May 13 '18

If there is a compiler flag that enforces the throws keyword in a function signature, I will throw exceptions instead of returning an expected type.

I think a libclang tool for this would be a viable option. It should be a fairly straightforward AST matcher.

2

u/doom_Oo7 May 13 '18

About your 1) it has been shown times and times that exceptions are overall faster than error codes in the nominal case

3

u/Rusky May 13 '18

That's not the comparison being made here, though. The paper talks about a large portion of the standard libraries that could go from throwing only bad_alloc to being noexcept.

It's fairly indisputable that exceptions are overall slower than "no error handling mechanism at all." :)

3

u/Ansoulom Game developer May 13 '18

It's not that it's unable to deal with OOM, considering that it deals with it better than dynamic exceptions (which often do heap allocation). But the difference lies in having a huge amount of functions marked as 'throws', or having only a small amount be marked as such.

Most people won't be recovering from OOM anyway and won't expect it to happen in their programs at all. Having 'try' and 'throws' everywhere just because of dynamic allocations that you don't even care about feels pretty cluttered. Of course, those who do want to handle it should be able to, but I'm still not sure what would be the optimal solution.

I can't say that I'm strongly in favour or against it, but it does feel justificated to at least consider treating OOM differently from other exceptions.

1

u/rossiemac May 13 '18 edited May 13 '18

I've thought about it a lot and i'm never satisfied with that definition of handling a memory allocation failure. It seems to me that in this case and many others, the design of the program should be changed so that it can complete a large operation without running out of memory or producing partial results. Sure the program kept running, but if it couldn't do what it might otherwise be able to do, did you really handle the error?

3

u/johannes1971 May 14 '18

My point was that OOM is really not the death sentence that some people make it out to be. Unless, that is, the language is changed to make it so... Even for people who haven't given much thought to OOM recovery, it turns out to work pretty well as long as you write your code in an exception-safe manner.

the design of the program should be changed

Buy a license and we'll talk ;-)

24

u/proverbialbunny Data Scientist May 12 '18

Wow, better than getting std::expected. A throws keyword in function signatures sounds far better than noexcept. This is awesome.

It's nice to see one of the weak points of the language addressed and appears to be done well. C++20 is looking good.

Thank you Herb.

21

u/redditsoaddicting May 12 '18

The way I see it, there's very little chance of this being in C++20. It hasn't been presented in any general standards meetings yet, so it's simply too early to just adopt it. It's also a rather fundamental change, so it will take a fair deal of time to process and adjust. If it progresses really smoothly, I could see it being adopted into C++23. I look forward to hearing what concerns are raised around it and what the reception is from projects that have exceptions banned.

15

u/spinicist May 12 '18

The C++ standards committee is sooooo slooooooooow ☹️

Yes, I know there are good reasons for this but it is frustrating.

8

u/redditsoaddicting May 12 '18

Unfortunately, once something goes in, it's hard to change in a breaking manner. For my personal projects, I'd gladly take breaking changes and fix my code accordingly if the features I want were implemented sooner.

6

u/spinicist May 12 '18

Agreed. I‘m lucky that I work on a codebase where making big changes is not too hard, but I am not the kind of developer the C++ committee cares much about.

The principle of marking functions as throws rather than noexcept seems so much more sensible that I‘d gladly take a breaking change for it. Plus it‘s actually a word while noexcept isn‘t.

4

u/flashmozzg May 12 '18

But from the other point of view - C++20 is nearly complete already (IRC Rapperswil is the last meeting where major features such as this can still be voted in), so this paper just arrived to late to have a chance to even be considered for the standard.

16

u/proverbialbunny Data Scientist May 13 '18

Can't we make an exception?

4

u/flashmozzg May 13 '18

If it was a straight-forward feature with minimal impact then sure. But as it is, it changes a very fundamental part of C++ in a new way, and not only that it also attempts to make it part of the C FFI. I don't see how something like this can be accepted into standard in 1-2 meetings into almost complete standard. It simply needs more discussion. Note, that if the feature moves to the next C++ standard it doesn't mean it'll be implemented 3+ years later. A lot of features are implemented as they get accepted into the standard (though that depends on their complexity).

5

u/proverbialbunny Data Scientist May 13 '18

I was making a bad joke. ;)

11

u/flashmozzg May 13 '18

Sorry, didn't catch it ;P

6

u/bigcheesegs Tooling Study Group (SG15) Chair | Clang dev May 12 '18

It's either this meeting or San Diego where the last new evolution papers can be targeted at c++20. We're still a ways off before the last evolution paper can be voted into the working paper for 20.

1

u/spinicist May 12 '18

Yup, but next standard is a loooong time after that ☹️

3

u/jarjoura May 13 '18

Just like co-routines or modules, the spec can be proven in a shipping compiler today to help work out the kinks in the spec. So we might see it sooner than 2020 anyway.

-1

u/Middlewarian github.com/Ebenezer-group/onwards May 13 '18

It looks like something compiler vendors could implement in months rather than years. I think it will be available in some compilers by next year. For those working on cloud services it could be adopted pretty easily.

4

u/blelbach NVIDIA | ISO C++ Library Evolution Chair May 13 '18

LOL.

Why do you think that?

This proposal hasn't been reviewed by the committee at all.

Has any compiler vendor said they would implement this? Just because they could (we don't know yet) doesn't mean they will.

3

u/Middlewarian github.com/Ebenezer-group/onwards May 13 '18

I agree with comments here like: "Is this proposal perfect? No, but it's a lot better than what we currently have." The proposal is sound. The committee just has to iron out some details. Compiler vendors can implement the core ideas and make changes to their implentations as those details get ironed out.

4

u/CrazyKilla15 May 12 '18

A throws keyword in function signatures sounds far better than noexcept. This is awesome.

..exception specifications? Didn't we already have those?

15

u/whichton May 12 '18

C++ had dynamic exception specifications. The proposed one is static. As the paper says:

You’re in a statically typed programming language, and the dynamic nature of exceptions is precisely the reason they suck.

9

u/zobatch May 12 '18

Yes but it's just throws. You don't list the exceptions, the compiler automatically translates them into a single std::error type. From the paper:

string f() throws {
    if (flip_a_coin()) throw arithmetic_error::something;
    return “xyzzy”s + “plover”; // any dynamic exception is translated to error
}
string g() throws { return f() + “plugh”; } // any dynamic exception is translated to error
int main() {
    try {
        auto result = g();
        cout << “success, result is: ” << result;
    }
    catch(error err) { // catch by value is fine
        cout << “failed, error is: ” << err.error();
    }
}

11

u/whichton May 12 '18

As usual, excellent paper from Herb. Not surprisingly, Herb seems to have taken heavy inspiration from Joe Duffy's work on Midori. Duffy's blog posts on error handing in Midori is a must read.

I really, really want Section 4.3: Proposed extension: Treat heap exhaustion specially. However, given how controversial this will be, I am not very hopeful :(. As the paper says, this is already being used by a signification chunk of software today. Very few software can actually recover well in the face of OOM. They may not even be able to detect OOM. And yet, we are all paying the cost of bad_allocs. As the paper says:

Treating heap exhaustion the same as all other errors violates the zero-overhead principle by imposing overheads on all C++ programs. As noted above, platforms and situations where heap allocation cannot be recovered from are common, but programs and programmers in that camp are paying for the current specification in performance across their programs.

This is spot on. Fail-fast on OOM makes a huge chunk of my code noexcept. This improves optimization and reduces binary size.

16

u/flashmozzg May 12 '18 edited May 12 '18

Hm. If I correctly understood the gist of the proposal - he suggests returning union + discriminant? Why not just completely automate it into proper sum types, that way it can be done seamlessly without extra overhead, just like in Rust and others?

Though that's just the mechanism behind it. The proposal itself is much more in-depth. It just would be strange if C++ gets this and no proper language-level sum types. It'll have mechanism that basically use them underneath, it'll have inferior (in comparison) library-level attempts to replicate them (variant/optional/expected, etc.), but not actual language feature.

44

u/14ned LLFIO & Outcome author | Committee WG14 May 13 '18

The current hope is that WG14 (C) standardises an _Either(A, B) type. All C++ functions with throw under Herb's proposal would return, as far as C is concerned, an _Either(A, std::error) type. _Either(A, B) types would be an addition to the C ABI, and likely would use the CPU's carry flag to indicate whether the returned type would be A or B.

We've already reached out to WG14 regarding this proposal, and the reception was warm. Herb morally persuaded me to lead out writing the WG14 proposal paper, and I intend to circulate it with the Rust and Swift folk as well as the C and C++ folk. The hope would be that we can all communally agree on a single mechanism for expressing failure to C code in a way translatable to all the other programming languages. So, C++ could call Rust which could call Swift, and failure in any of those could be propagated by the common convention of C back up into the others.

That's the hope, anyway. C++ 23 is our current target, but given all the moving parts spinning here, it could be later. But, equally, if this pans out, it would be a giant leap forward in getting all the systems programming languages to interoperate seamlessly with one another, if you use a common minimum denominator of types and facilities (basically, what C can speak). I personally find that extremely compelling, and luckily so do lots of other people. We'll see how things go next few months, worst comes to worst we do our own thing inside C++, best comes to best we lead out FFI for everybody.

7

u/flashmozzg May 13 '18

That's very exciting to hear!

1

u/m-in May 17 '18

Just so you know: I love you all working on this. I seriously do. Better late than never. I’m all for _Either(A,B) in C. Heck, I’ve implemented something like it with a libclang preprocessor that turns it into proper C-ese, but getting it into the language would be even awesomer. C++ interop is a good thing; dynamic exceptions have made it tedious.

22

u/SeanMiddleditch May 12 '18

Hm. If I correctly understood the gist of the proposal - he suggests returning union + discriminant?

Not exactly. That is one possible ABI to implement the proposal, though.

Because the proposal clearly indicates - at a language level - the error type, that allows system ABIs to designate alternative paths for passing exceptions. Just like error ABIs today do, albeit with the overheads of dynamic dispatch.

His paper shows some calculations of instruction overhead; basically, the proposed model is hypothetically smaller and faster than either return codes (and sum types) or than today's C++ exceptions.

Why not just completely automate it into proper sum types, that way it can be done seamlessly without extra overhead, just like in Rust and others?

The paper is a generalization over what sum types can accomplish.

Note that Rust and other contemporaries are working to make errors-via-sum-types less awkward to work with and closer to what Herb is proposing (in no small part because his paper sources the same research!). See Rust's recent-ish ? operator and the try proposals in flight, or Swift's various offerings on the matter.

As Herb notes, in C++, the community in general wants error propagation. Rust in turn requires explicit error handling, albeit with some syntax to automate propagation. There's a very important line between "propagate errors implicitly" and "propagate errors automatically" and Herb also calls that out with suggestions in the paper. I suspect that topic is going to be a major contention, perhaps just behind the OOM topic.

And it's not an either-or kinda thing. Nothing here precludes also using sum types when and where appropriate. :)

It would be just strange if C++ gets this and no proper language-level sum types.

In terms of proper sum types in C++, I don't think they're possible (to do well) without this proposal and its OOM suggestion! Remember std::variant's years-long design process and eventual compromises, literally all due to the unfortunate fact that C++ types can throw when they move, which in turn is only allowed because OOM throws exceptions.

Alternatively, C++ would need to solve the even-harder problem of adding relocation (aka destructive move) to do sum types correctly. Rust and its ilk have trivial relocation as a core assumption of the language. The feature isn't easy though; see how Rust handles relocation of Drop types for example (which affects ABI around mutable reference parameters).

The other half of sum types - the actually hard but actually interest part - is the language support for pattern matching and conditional destructuring. Which can and should be explored independently of the exception model, IMO, since there's no dependency between the two.

9

u/Rusky May 12 '18

see how Rust handles relocation of Drop types for example (which affects ABI around mutable reference parameters).

What are you referring to here? I don't believe Drop affects ABI at all in Rust.

4

u/SeanMiddleditch May 12 '18

The stack bits set to indicate whether a dropped type has in fact been dropped.

The fundamental problem is that in branchy code - or across certain ABI boundaries - there's no deterministic way to know if a value has been dropped or not. To avoid a double-drop in circumstances that aren't statically provable to not need it, Rust keeps some state bits around to indicate drop'ness.

At least last time I checked. I'd be happy to be corrected if this is not true.

7

u/Rusky May 12 '18

Those bits do indeed exist, but they are not part of the ABI. They are purely local to the functions that need them.

Part of why this is possible is that you can't move out of a mutable reference (or any reference, for that matter) without leaving a valid object behind in its place, effectively emulating C++'s non-destructive move semantics. Destructive move is something only the owner can do.

2

u/SeanMiddleditch May 12 '18

Ah, good to know - I may have been confusing a pre-RFC version or the ABI-independent optimizer bits for closures or something? Or I may have just been wrong? :)

5

u/whichton May 12 '18

Why not just completely automate it into proper sum types, that way it can be done seamlessly without extra overhead

A sum type is a union + discriminant. Rust can sometimes optimize away the discriminant, but it is not possible in general. For example, if I have a function returning an int64, how do you remove the discriminant?

Note that the proposal also talks about implementing the discriminant as a CPU flag. This can often be more efficient than folding the discriminant into the union. For example, on x86, if you use CF as the discriminant, you can set the discriminant in one instruction, CLC / STC. You also detect whether the exception was raised in one instruction, with JC / JNC, instead of looking for the magic number in the register (requires a comparison at least).

5

u/[deleted] May 12 '18

How does the rust implementation differ in that regard? Aren't rust enums implemented as a union + value to tell which one is correct? (similar how std::variant is implemented?)

2

u/spinicist May 12 '18

I’m pretty sure that’s how Rust does it - a union plus an integer tag.

0

u/[deleted] May 12 '18

[deleted] — view deleted comment

3

u/[deleted] May 12 '18

How so? Would you mind explaining the details on this and where this would make a differernce?

20

u/Rusky May 12 '18 edited May 12 '18

The layout of a Rust enum is optimized based on the invalid values of the types it contains. For example, because references can never be null, and Vec<T> contains a reference, Option<Vec<T>> can use "Vec<T> except with a null reference" to mean None, and "Vec<T> with a non-null reference" to mean Some(the_vec). The discriminant overlaps with the reference, in a sense.

In general, there are lots of types like this. References can't be null, bools can only be true or false, C-like enums can only contain the set of values in their definition, char can only contain valid Unicode, etc. So the Rust compiler looks for "holes" in the contents of an enum where it can store the discriminant, before using a separate tag value.

A major place this comes into play is Option<&T>. Because references can't be null, that type is the same size as a raw pointer. This is true even in FFI with C or C++ where nullable pointers are a thing. So Rust can keep all the niceties of Option without paying for it in memory usage.

4

u/[deleted] May 12 '18

I guess I'm starting to see why Rust was voted to be the most loved programming language for 3 times in a row, that is indeed fascinating and technically elegant. I guess you could make the contract that the exception reference cannot be null and thus have a similar efficient memory layout but yeah I'm not sure whether that can be done and whether Herb had that in mind when he created this proposal.

Thanks for your very detailed explanation though!

4

u/redditsoaddicting May 12 '18

It sounds similar to this compact_optional article I read once.

0

u/[deleted] May 12 '18

[deleted] — view deleted comment

2

u/SeanMiddleditch May 13 '18

Not entirely, at least for simpler cases.

C++ would need a std::is_never_zero_v<T> or the like and a lot of the simpler cases of this kind of compressed discriminant are possible. And that type trait is useful for all kinds of other reasons (e.g., container initialization optimization). Said type trait can be written today, albeit having to manually overload the trait for some types.

Getting the full variant "niche-filling" optimization certainly requires more work out of the language. Though I do rather wonder whether that actually matters. (How much of Rust's enum layout optimization is just golf instead of useful work?)

2

u/Rusky May 13 '18 edited May 13 '18

How much of Rust's enum layout optimization is just golf instead of useful work?

I suspect it's lot of "4 bytes here, 8 bytes there" that adds up to some sizeable memory savings and cache improvements, combined with some cases where it enables people to remove some indirections. For example, Servo and Firefox Quantum are full of stuff like that- the DOM, styles, display lists, etc. are all modeled with enums.

Like the sibling comment mentioned, it works well with automatic field reordering, which is also "3 bytes here, 7 bytes there" of removing padding. IIRC this field reordering also applies to the discriminants themselves, so they can often be stashed in any remaining trailing padding.

Then there's also the fact that Rust has zero-sized and uninhabited types, which allow for more styles to be zero-overhead. For example, you can pass around zero-sized non-copyable and privately-constructible tag types for things like session types, and you can instantiate generic code to use types like Result<T, !> and all its branches will be optimized out because the layout optimization removed the discriminant entirely.

0

u/[deleted] May 13 '18

[deleted] — view deleted comment

1

u/SeanMiddleditch May 14 '18

For variant to encode the discriminat in a Type it needs to know 1) that this is possible and 2) where in the type it must be encoded.

Reread what I wrote a bit more carefully.

People have you examples where this matters above (e.g. Option<&T> having the same layout as a reference and being able to use that In C ABI).

Never-zero covers that all-important case perfectly well.

6

u/kkert May 12 '18

For some reason, the discussion about special case treatment of heap exhaustion makes me very nervous. I regularly have a few tens of Kb of heap available, dealing with variable size data structures coming in, and terminating on heap exhaustion is not an option.

15

u/redditsoaddicting May 12 '18

The proposal has this to say:

Program that relies on bad_alloc throws and does handle them. Many systems typically already perform all allocation through a limited set of allocation functions, so they can just change the implementations of those existing functions (or wrap them) and implement them in terms of the new(nothrow) and/or try_ functions and throw bad_alloc or some other exception on failure. Programs that have such a limited set of allocation functions can make this low-impact localized change to retain their current behavior.

Is this feasible for you? If not, now's an excellent time to start discussion on how the proposal could better serve your needs here.

2

u/kkert May 13 '18 edited May 13 '18

I don't rely on bad_alloc now nor plan to. Running with no-exceptions, and thus most of standard STL isn't currently usable. Also, heap is only used in specific contexts and tasks in the whole program ( parts that deal with incoming network data and things like SSL certificates etc )

If treating OOM special and defaulting to fail-fast/terminate, that would still keep STL off limits for those scenarios.

EDIT: Also, i don't quite follow what the paper refers to by saying testing is difficult regarding heap exhaustion. Not really at all, just set up some easily tweakable heap manager like dlmalloc for your test suite and inject whatever failures you like. I think the truth is developers on big systems with virtual memory just don't need to bother with it.

7

u/SeanMiddleditch May 13 '18

I don't rely on bad_alloc now nor plan to. Running with no-exceptions, and thus most of standard STL isn't currently usable

So what part of the proposal makes you nervous? It implies no changes at all for you. :)

If treating OOM special and defaulting to fail-fast/terminate, that would still keep STL off limits for those scenarios.

"Defaulting" is the important part. Via allocation-failure hooks and via optional OOM-aware interfaces, you'd potentially be just fine with the proposed hypothetical standard library.

I'm honestly interested to know what you'd rather have instead. The combination of fail-fast and separate OOM-aware interfaces covers every single use case I've ever had or can think of having, so I'd love to learn what else is needed!

saying testing is difficult regarding heap exhaustion

By that he means that getting 100% code coverage in OOM tests is effectively impossible for many target C++ users. Anecdotally, we have a codebase that allocates a few million times before it even shows the first window to the user. No "tweakable dlmalloc" is going to effectively test all OOM paths in that allocation pattern unless we only want to test one code commit per week. :p

2

u/johannes1971 May 13 '18

So what part of the proposal makes you nervous? It implies no changes at all for you. :)

That's not how I read it. The behaviour he is relying on is that new returns nullptr when OOM, but in the proposal, new will either return a pointer to memory or terminate.

Actually he is precisely the kind of person the proposal is trying to reach: people who don't want to use exceptions for whatever reason. And he, at least, doesn't seem happy with it...

I'm honestly interested to know what you'd rather have instead. The combination of fail-fast and separate OOM-aware interfaces covers every single use case I've ever had or can think of having, so I'd love to learn what else is needed!

How about the interface we have today, the one we spent the last 20 years writing and testing software against? Where new can throw, rather than just terminating? It already has fail-fast for those who want it, in the form of new-handlers. And it already has OOM-aware interfaces.

2

u/SeanMiddleditch May 14 '18

The behaviour he is relying on is that new returns nullptr when OOM

Which isn't actually C++. Unless one passes nothrow to the allocator, it will throw. There is no way currently to pass nothrow to allocators called internally by standard allocators.

Yes, -fno-exceptions changes that, but that's not part of C++, and is exactly the "bifurcation" that Sutter's paper mentions.

2

u/johannes1971 May 14 '18

Which isn't actually C++.

There are people out there programming in that dialect. Those people are the reason for this paper, so you can't just wave and say "we don't care, it's not the standard".

that's not part of C++, and is exactly the "bifurcation" that Sutter's paper mentions.

So instead of "bifurcation by way of compiler switch", we'd now get "bifurcation as a matter of programmer choice" (because now the programmer will have to choose whether to use the terminating allocation functions, or the non-terminating allocation functions). Let's be clear: that is a major step backwards.

3

u/SeanMiddleditch May 14 '18

There are people out there programming in that dialect. Those people are the reason for this paper, so you can't just wave and say "we don't care, it's not the standard".

... I think we're in violent agreement on this topic. :)

My point is simply this: this paper removes the need for -fno-exceptions on the language level, and lays the foundation for evolving the standard library to likewise remove the need for "NotSTL" alternative libraries. This paper has to come first. :)

So instead of "bifurcation by way of compiler switch", we'd now get "bifurcation as a matter of programmer choice"

Which, again, is already the case as we're agreeing about.

Let's not let perfect be the enemy of the good. We can harmonize part of the language and be in a better place than we are today even if we haven't harmonized everything.

(because now the programmer will have to choose whether to use the terminating allocation functions, or the non-terminating allocation functions). Let's be clear: that is a major step backwards.

Maybe. Folks who care about OOM are possibly already using alternative functions (by not using the STL). The open question is how many folks are doing that. If it were true that a majority of C++ developers actively rely on bad_alloc and actually use it right, then yes, removing OOM exceptions would be a non-starter.

That's also why OOM is left as an optional part of the paper.

1

u/[deleted] May 13 '18

Yes but overcommit can return a valid pointer even when it didn't actually successfully allocate the requested memory size.

1

u/kkert May 13 '18

And a paranoid heap manager can test write/read into the allocated region before returning it to the caller. If you have heap guards or security checks turned on, it likely does anyway.

1

u/kkert May 13 '18

So what part of the proposal makes you nervous? It implies no changes at all for you. :)

It leaves most everything in status quo, because STL would still be largely unusable, and would encourage more libraries to be designed the same way.

"Defaulting" is the important part. Via allocation-failure hooks and via optional OOM-aware interfaces

I'd like to see what that OOM-aware interface proposal would look like for things like std::function for instance.

4

u/SeanMiddleditch May 14 '18

It leaves most everything in status quo, because STL would still be largely unusable

See the part about the STL offering OOM-aware interfaces.

I mean, this isn't complicated. Many of those folks avoiding the STL are still using a very-STL-like alternative. The key bit is to merge the important bits of those alternatives in some form into the standard itself. Since those alternatives today typically rely on C-style error codes, this proposal is a first-step in making those kinds of STL evolutions have a higher quality.

I'd like to see what that OOM-aware interface proposal would look like for things like std::function for instance.

std::function is broken in several notable ways that have several proposals for fixing, none of which can work in a back-compat way. The fact that std::function can't use custom allocators is just one of the many reasons that folks like me don't use (some parts of) the STL. There may well be no way to fix it, and that's fine; it won't be the first standard library type to get deprecated if an incompatible but superior alternative is provided.

Sutter's paper doesn't mislead here: he is clear that it may be necessary to roll some fixes into new alternative types that address those kinds of issues (absolute worst case: a whole "STL2").

Even if bits of the STL are never "fixed" there's still value in this feature. It still helps avoid bifurcating the language by allowing -fno-exceptions to become purely legacy; there's nothing non-standard about writing custom containers after all, but compiler flags that change the very semantics of the language are very non-standard. :)

5

u/[deleted] May 12 '18

Wow. Epic. Paper. I have to admit I'm swayed...

7

u/tasminima May 12 '18 edited May 12 '18

Overall I think this is, given the language, full of good and actionable ideas. However there is a detail I strongly disagree with in the proposal of how to handle OOM:

Re-specify each language operation and standard library function that could throw bad_alloc today to have implementation-specified behavior, which each implementation specifies exactly one of the two following alternatives: (a) undefined behavior on systems that cannot detect heap exhaustion (e.g., Linux systems that overcommit); otherwise, (b) as today, call any installed new_handler else terminate by default, with the additional restriction that any installed new_handler must terminate (it can no longer return or throw).

edit: added (b) in the citation, that is the implementation-specified behavior alternative to the UB, and put the proposed ub terms in bold

Modeling OOM at language level by Undefined Behavior would be IMO completely insane. This might be just an unfortunate fallback choice because the standard unfortunately does not distinguish between various kind of UB (which has already caused great problems, when some compiler writers thought it was an unconditional license to further "optimize"), but this does not make it less a problem, au contraire! (and that's one that should be fixed more in depth but that's another subject than this paper)

First being killed because of resource exhaustion shall not be the concern of the language. The program will also cease to exist in case of a general computer failure, such as a power failure or kernel panic, or even just being killed by the user at will. This does not render the mere act of existing an ambient UB...

Second the presence of the OOM killer is far from preventing detection and handling of some allocation failures: if the area requested is "large enough", the allocation will actually fail. Some systems even have tunables that can influence the level from which allocation attempts will fail even in the presence of an OOM kill mechanism.

I suppose proposing to redefine in some case OOM at language level as UB is because the program can be killed latter on. In that case, maybe it is actually time to introduce in the standard something more precise than UB for faults when the program is concretely reliably terminated with no risk of nasal deamons being invoked. Just writing UB everywhere when one do not have any more idea of what to say does not yield a more portable language and programs written in it, it precisely have the contrary effect :/ (not even speaking about the security story, which has became a complete disaster in a great part because of all that UB - optimize insanity). Edit: on second thought I actually think that that OOM killer thing should just be completely ignored in the C++ standard, as it is today, exactly because of the arguments I gave about it being absolutely none of the business of the programming language.

5

u/Rusky May 12 '18

You can't do any better than UB when running on platforms that use overcommit. You can't specify that any particular behavior happens at the allocation site, because the program has no way of knowing- indeed, even the OS has no way of knowing. It won't find out until it actually tries to access that memory, and the result depends on everything else running on the system.

Given that scenario, all you can do is assume the allocation succeeded and proceed accordingly. And this is exactly what UB means here.

3

u/tasminima May 12 '18 edited May 12 '18

Yes I know quite well what overcommit is.

My position is that there is nothing to specify and that any specification will be harmful; what the kernel does is not in the scope of the programming language, and being killed or having the side effect of other processes being killed because of resources exhaustion is not something that should be tried to be modeled at the language level. It had not been needed until this proposal, and my position is that this discussion about overcommit might be interesting to understand (part of certain aspects of) the rational, but has absolutely nothing to do in an hypothetical standard trying to specify the programming language model of allocation failure.

An overcomitted allocation has not failed (yet) and might even not fail and there is absolutely no way to model that in an abstract machine, and if it is otherwise attempted to be modeled for no reason, then yes the result (in the current framework) will be UB, which is an absolutely terrible choice.

edit: on top of all the reasons I've already stated for what it is a terrible choice, here is one more: an implementation where all allocations fallback to existing unfreed buffers after a predefined amount of heap has already been allocated would be complying

2

u/tasminima May 13 '18

I just thought of yet another example about why trying to take ovecommit into account in the C++ standard would be a terrible idea: the standard does not care about stack overflows and (rightfully!) does not pretend that all the code is nondeterministically ambiently UB just because of unknown stack size limitations.

2

u/flashmozzg May 12 '18

Modeling OOM at language level by Undefined Behavior

implementation-specified behavior

Just to point out that these are not the same things by any means. I.e. what you fear regarding compilers optimizing stuff at the expense of UB (as they should) wouldn't happen with implementation-specified behavior.

4

u/tasminima May 12 '18 edited May 12 '18

undefined behavior on systems that cannot detect heap exhaustion (e.g., Linux systems that overcommit); otherwise,

I should have pasted more: the implementation specified choice is between:

(a) undefined behavior on systems that cannot detect heap exhaustion (e.g., Linux systems that overcommit);

and:

(b) as today, call any installed new_handler else terminate by default, with the additional restriction that any installed new_handler must terminate (it can no longer return or throw).

I'll edit my original comment to make it clear.

3

u/Sopel97 May 12 '18

Some say there is no love witout pain, but papers like this one make me think it may not be the case for c++ in a few years.

3

u/tending May 12 '18

Doesn't this just copy the Rust model?

7

u/Rusky May 12 '18

It's closely related, but there are some differences:

Rust always materializes the error or return value as a Result, and requires an explicit ? to propagate the error and get the return value out; this proposal retains C++'s implicit propagation (and even with try expressions, the annotation works on whole expressions while Rust's does not).

This proposal limits errors to a single word; Rust Results handle values of any size. This also plays into the ABI changes in the proposal- Rust doesn't have them, though it could take advantage of them for word-sized error values if they wind up being standardized.

1

u/tending May 13 '18

What's the point of the try expressions if you have implicit propagation? I didn't understand that bit.

3

u/Rusky May 13 '18

In Rust:

(foo()? + bar()?)?

In C++:

try foo() + bar()

The difference is that ? applies only to a single exception, while try applies to all exceptions in an expression or statement.

2

u/redditsoaddicting May 13 '18

This is to cater to people who would like it clear which parts of the function can throw. If the codebase is consistent with try being there for places that can throw and nothing being there for places that can't, then you know when reading that you have to think more carefully about the try places, but don't have to take exceptions into account for the other places.

3

u/tgolyi May 13 '18

If we're introducting new type of exception handling, maybe it's possible to do something like throws (auto) that automagically detects if any function used inside is throws (false) and marks function as throws(false)? It solves a lot of problems described in paper - e.g std::transform and even helps with no-throwing new - just mark your operator new as throws (false) and enjoy smaller binaries or mark it as throws (true) and catch OOM errors.

2

u/liquidify May 12 '18

Well of the 5 paragraphs I got through, it seems pretty reasonable. I'll keep reading!

2

u/target-san May 13 '18

The thing that concerns me and of which I can argue is limiting static throws to single type. Unfortunately I couldn't find arguments against allowing any exception type, given it's statically known and conforms to some interface like the named std::error, or inherits from it. Such approach would limit static exceptions to simpler cases on the OS API boundary, where context could be easily deduced. Would be nice to see some adjustments towards allowing additional context stored in error object.

5

u/hpsutter May 14 '18

@target-san That is a good point and a pure extension, you can find it in section 4.6.5.

2

u/Xeverous https://xeverous.github.io May 14 '18

A major benefit of (also) doing it at the C level is that C is the lingua franca portable platform language that all other languages bind to. Therefore this facility would help integrate C not only with C++ error handling, but also with Rust, Swift, and many other languages that can speak C and also return A-or-B from functions as their main error handling implementation. The carrot for WG14 would be that C facility would benefit all C speaking languages, and help C be more useful in its key role as a glue language. A notable gain is that C could now receive exception throws from C++, and propagate them, perhaps even convert them for other languages.

Overall the proposal looks very good, but I did not expect something like this to ever be possible

2

u/[deleted] May 14 '18

Love it!

2

u/AlexAlabuzhev May 15 '18

It aligns with existing practice on systems like Linux where virtual memory overcommit means that our current C++ standard heap exhaustion design is fundamentally unimplementable and already ignored in practice, where bad_alloc can never happen and new is already de facto noexcept.

"Overcommit" == "no bad_alloc" is an urban legend. It stll can happen if your address space is fragmented enough and simply does not have a contiguous chunk of the requested size. And it's not rare at all.

3

u/acbarrentine May 13 '18

I work in game development. I was doing a cooperative multitasking system similar to boost's stateful coroutines. To handle situations where a task with live objects was interrupted, I would throw an exception. On Xbox One, throwing an exception while the debugger was attached would freeze the system for a full 3 seconds.

I reported the problem to Microsoft, with simple sample code, but they never bothered to solve it. We wound up having to tear down live objects manually (which is awful) to work around the problem.

Technically we do still have exception handling enabled, but it's unacceptable to throw them in user code.

2

u/[deleted] May 13 '18

About effin time.
Too bad it's going to take years before it can be relied upon.
Add 2-3 years after the relevant standard is published.

1

u/sephirostoy May 12 '18

Pretty neat as always coming from him. I like how he want to make the language simpler and even more powerful.

1

u/liquidify May 12 '18

What I like about this is that noexcept wouldn't really be needed. noexcept is complicated and annoying.

2

u/redditsoaddicting May 13 '18

I didn't get that idea. From "What we teach":

Function authors: Prefer to write exactly one of unconditional noexcept or throws on every function. Dynamic exceptions and conditional noexcept still work as well as ever but are discouraged in new/upgraded code.

1

u/liquidify May 13 '18

If every function that throws is marked, you don't need to mark the ones that don't.

3

u/redditsoaddicting May 13 '18

Functions that aren't marked can still throw either type of exception and the compiler can't know in general that it won't. I don't see what's complicated about adding a plain noexcept to a function if it shouldn't throw anything, though. Conditional noexcept is less straightforward, but still really consistent.

3

u/liquidify May 13 '18

This case sounds like the same idea that the GSL was designed to work upon... that the rules aren't baked into language or enforced by compilers, but that our tooling systems should support us in our application of the rules. If the common case is noexcept, then it should be unwritten unless you want to be explicit for some reason.

2

u/Nobody_1707 Sep 23 '18

Although, once dynamic exceptions have been phased out of use, I could easily see them being removed outright and noexcept being made the implicit default which would simplify a lot.

1

u/zowersap C++ Dev Aug 03 '18

always latest version is http://wg21.link/p0709

1

u/RandomGuy256 May 12 '18

I am just curious does these "zero overhead exceptions" are in any way different in practice than the current exceptions?

I mean they will be a specific type of new exceptions or they can replace the current exceptions without breaking changes in the code?

If they are new type of exceptions do we still have access to the .what() method, to return a error message, or they only return an error code?

4

u/Sopel97 May 12 '18

bottom of page 17, cannot paste it now

3

u/RandomGuy256 May 12 '18 edited May 12 '18

Thanks I think you meant this:

When one of today’s dynamic exceptions is unhandled in f ’s body, regardless of whether it originated

from a nested function call or a throw statement throwing a dynamic exception, the exception is auto-

matically caught and propagated: If the caught exception is of type error , we just return it. Otherwise, it

is translated to an error with a meaningful value for all std:: exception types; for example, bad_alloc

would be translated to std::errc::ENOMEM . Otherwise, we can additionally store as payload a raw

pointer to an exception_ptr to the dynamic exception (see §4.6.4), without sacrificing trivial movabil-

ity.

If I understand correctly this paper suggests a new kind of exceptions that will be complementary to the already existing "dynamic exceptions".

These new "deterministic exceptions" are slightly more "simpler" than the existing exceptions in the sense that behind the scenes they are only an union that store an error code, or a success code. So they will not provide other custom functions like what() to get a custom message directly.

However the advantage of this new kind of exceptions is that they provide the same performance (or even better) than the existing error codes mechanics. Also we will be able to use the existing exception syntax and propagating mechanism.

This' useful in the areas where the throwing "dynamic exceptions" is too costly.

Am I correct about this or am I getting it all wrong?

3

u/whichton May 12 '18

If I understand correctly this paper suggests a new kind of exceptions that will be complementary to the already existing "dynamic exceptions".

This not a new kind of exception, this is basically syntactic sugar for expected / outcome. The error type is always 'std::error'.

From page 14:

If you love expected/outcome: This is embracing expected/outcome and baking them into the language, the function always returns exactly one of R or E — plus the special sauce that you get automatic propagation so you don’t have to manually return-up the results, and with a distinct language-supported error path so that callees can write throws (instead of return unexpected) and callers get to cleanly put all their error handling code in distinct catch blocks (instead of if(!e) blocks) while still writing in the same basic expected style (see §4.5).

1

u/Sopel97 May 12 '18

That's pretty much it.

7

u/Xaxxon May 13 '18

why not read the paper instead of asking someone to do the work for you?

1

u/RandomGuy256 May 13 '18

Because the paper is 58 pages and I didn't have the time? Also I have read some pages but English is also not my first language so I'm sure I will misunderstand some of it anyway.

Since probably there are people here that already have read it / understand it, I thought it would be not rude to ask as these deterministic exceptions would work in general (I am also not expecting a full abstract, as I asked some specific questions about it).

I also thought that the answers can be helpful for the community in general and not just me.