r/cpp_questions • • 4d ago

OPEN Why are exceptions so "backstabby"?

Simply put, I often find myself being told that exceptions "are not that costly" and that "the compiler puts it on cold sections anyways".

As a forenote, I'm the kind of person who always does `-fno-rtti -fno-exceptions` as I value code size usage (I develop small embedded shit and such, which does lead me to decorate functions with alignas and other thingies). Sometimes I also drop using the libc/libc++ and do syscalls raw because I can't stand the overhead (malloc/operator new is a great general purpouse allocator, but it doesn't suit my specific performance needs for example), so I take the hit from doing a syscall for a big mmap and then manually allocate memory by using fixed upper bounds.

(Ok also because glibc malloc sucks, but that is another topic)

Now with that noted, I have one pique in life: Why should I even use exceptions?

I often find myself removing exceptions of whatever codebase I happen to contribute to. Which does lead to people telling me that "you shouldn't do that".

The reason they often cite is either:

- It's not that important in the grand scheme of things (Valid, but so is every 'death by a thousand cuts')

- It makes code less clear (I'd argue otherwise)

- It's standard/idiomatic (Yeah and so is std::auto_ptr)

I really want to know WHY should I even use exceptions. I feel like they're a waste of language grammar I'm forbidden for touching, for it would bring me great despair.

As a cited case; recently I was working on optimizing a JSON parsing loop (oh scary). Obviously the final solution was not using JSON and just doing raw text with the |0x202020 casecmp trick.

But after collecting the values on a vector (I'd rather prefer a VLA to avoid indirection btw) I saw that the specialization of the vector for the non trivial class did in fact make a bunch of garbage for a case that I would have not hit otherwise.

https://godbolt.org/z/MPb9xnYqx

Like this is dumb, I'm not developing code for an airplane, if the thing runs out of memory it's just gonna crash anyways.

And no, noexcept also sucks because it just wraps shit around {} with std::terminate(), which is dumb (atleast on MSVC, but whatever).

36 Upvotes

65 comments sorted by

66

u/FancySpaceGoat 4d ago edited 4d ago

The single biggest reason is simple: With exceptions, you can error-out of a constructor.

And when you can error out of constructors, you can establish *really* tight class invariants, which is a great way to keep your codebase stable and extensible in the long run. Tight invariants also lets you get rid of a bunch of preamble `if(this_is_in_a_sane_state)` at the top of all your public methods. Anything part of the invariant can be safely assumed to be true *no matter what users of the class do with it*.

The second (less important in my book) reason is that if you know that errors are rare, exceptions let you keep a bunch of branches out of the happy path of the program (at the cost of making the unhappy path *really* unhappy).

28

u/MooseBoys 4d ago

> you can error-out of a constructor

While exceptions are technically the only way to do this, it’s much better IMO to skip them and use the factory pattern to achieve the same effect i.e. static method `Foo::Create(…) -> result<Foo>` along with `Foo() = delete` means that you can never have a Foo in a partially constructed state.

13

u/FancySpaceGoat 4d ago

Yeah, that's fair, but then you lose the ability to construct instances inline. That's often fine, but not always.

9

u/MooseBoys 4d ago

Yeah one of my favorite rust features is the ? operator which basically turns this:

auto result = Foo::Create(…);
if (result.err()) return err;
auto foo = result.take_value();

into this:

let foo = Foo::Create(…)?;

3

u/bert8128 4d ago

Are you passing back an optional of Foo either the create function? And then call isvalid (or whatever) afterwards? I think for truely exceptional cases (really, I’m not expecting this to fail) I would prefer to avoid littering the code with isvalids which hardly ever return false, and have an overarching try/catch in one place (perhaps main) to identify would went wrong in this rare case. Of course if the error is not exceptional (happens sometimes, handled nicely) then the create/isvalid option is fine.

3

u/MooseBoys 4d ago

expected<Foo, Err>, or some polyfill equivalent. If something's truly unexpected I prefer to just abort.

2

u/Loose_Low8543 4d ago

I always have one rule to myself is that constructors are pure functions, and at most load/store

Otherwise you end up with the abhorrent "OpenGL as constructors" pattern... or god forbid the "Vulkan as constructors pattern".
I also rather much prefer a whole handling instead of per object (i.e fail for a list of, not for each individual element of)

So I do see this as an anti pattern. If I want to keep my codebase stable I just use the guarantees provided by the type system itself. If no error can occur then no error can be checked for. Callers are responsible to assert this (where reasonable). If it needs to be on a constructor, then no, keep it trivial, make a separate method like `init()` or whatever.

13

u/FancySpaceGoat 4d ago edited 4d ago

Consider something like a class that holds a pointer to a system window (that can fail to be created). If you have the invariant "If I have an object to my window class, then the system pointer is valid", and throw in the constructor if you can't make it happen.

From that point on, you *never* have to null-check that pointer no matter what sequence of public methods are called on the class. You can just assume the pointer to be non-null because the constructor would have thrown otherwise.

And that's just one example.

2

u/Loose_Low8543 4d ago

I think that is indeed a strong argument for invariance.

But I reckon; how many times does one actually have to null check a window?

It is not an invalid point, I can see why one would want to use such guarantee.

But I don't think the way it's implemented currently makes such thing worth considering from a codegen view. I have seen compilers make good throw/catch codegen, but often the way it is done leads to poor codegen, often (libc++ is the greatest offender of this behaviour). Doesn't hurt in the grand scheme of things but again, that's a pique.

But I reckon: Why not just check after the construction? It's less code for the same result (destroying object after creation when one component fails to materialize). And in most arches its just cmp + jmp.

11

u/FancySpaceGoat 4d ago edited 4d ago

> But I reckon; how many times does one actually have to null check a window?

If the window pointer can be null at the exit of the constructor: In every single public method that uses it.

A class' behavior should be well-defined for any permutation of calls to its public interface.

That's like half of the reason behind wanting encapsulation in the first place..

4

u/BrotherItsInTheDrum 4d ago

I'm generally on the side of "exceptions good in moderation," but I want to point out that you can get the same property of "invariants always hold no matter what sequence of public methods are called" by using a public factory function and private constructor.

8

u/SoerenNissen 4d ago edited 4d ago
  • It makes code less clear (I'd argue otherwise)

and

If it needs to be on a constructor, then no, keep it trivial, make a separate method like init() or whatever.

You're allowed to be wrong but you shouldn't be wrong in other people's code base. init() is hot garbage, what do you mean there's an object that's left the constructor but not finished constructing?

-4

u/Loose_Low8543 4d ago

A trivial object should be 0 at construction, then at `init()` filled with valid data.

Deriving from DoD principles, a 0-object doesn't lead to a crash, but its "pointers" point to the 0th object (an invalid/scratch space). Of which can easily be filled with actual invalid (all 1s) data, to trigger a visible crash.

An explicit `init()` isn't universal on my code (I reserve it only for objects whom can be initially filled with uninitialized values, or, rely on .bss clearance for them to be 0).

Obviously uninitialized is bad, but initialized-as-zero is good (and its just memset). Which is the point of `init()`. (Also allows emplace-ment).

9

u/SoerenNissen 4d ago

There are objects that are wrong when memset to all zeroes.

It is fairly clear from your messages that you code in a particular style that I've seen before, and it would not benefit from exceptions. The order is

  • step one: remove error-inducing patterns from code
  • step two: without those patterns, exceptions can make code clearer and more correct

so since you're still using the error-inducing patterns, you should not adopt exceptions.

13

u/FancySpaceGoat 4d ago

If you choose not to make use of OOP in C++, that's your prerogative.

But then don't be surprised if the OOP language that you are using sans-OOP has features that don't serve any purpose for you.

2

u/bert8128 4d ago

Instead of construct then init, have you considered using a POD struct to hold the data, and have the only constructor take one of those structs? Then you never have an object with no useful state.

3

u/Business-Decision719 4d ago edited 4d ago

In a lot of peoples opinion, any object should have everything it needs to be "valid" at construction, and lose it upon destruction.

Manual "init" and "cleanup" defeat the purpose of even having constructors and destructors in the first place. They sit around being forgotten or getting called twice by mistake or getting called at the wrong time, potentially across multiple threads, and inevitably someone's left with a seemingly usable object that either got cleaned up already, it hasn't been initialized. They're bug vectors. RAII is all about getting rid of those.

An explicit init() isn't universal on my code

Exactly. Because it's usually terrible, outside of whatever kinds of objects that you can "reserve" it for.

You don't have to like exceptions. But the reason a lot of people like using them, most especially in constructors, is because they essentially force the process to grind to an uncermonious halt immediately if any of the raw materials is missing. There's a reason the object couldn't be constructed, and these people want the program to either catch the exception and respond or just crash and tell them what was unavailable, rather than burdening the team with having to solve the mystery of some random error that turns out to be a risky method call on some zombie object.

The people who are doing this care about that extra guardrail more than they care about the cost of exception handling. If you don't, then their coding style isn't for you. You can disable exceptions and try to make do with manual init where you can in your projects. People who set up everything in a constructor and throw exceptions when they can't are still going to complain if you come in and try to bring your practice into their codebase and mess up their sand castle.

3

u/FancySpaceGoat 3d ago edited 3d ago

I am (obviously) one of those people and I think it's worth expanding on that a bit.

For me it's not so much about *guardrails* in the safety net sense. Rather, it's simply about creating guarantees that the program won't exhibit any Undefined Behavior. I think the distinction matter. "guardrails" can often mean defensive programming, which is something I *loathe* with the passion of a thousand burning suns.

One of my job, as a C++ programmer should be to write programs that never exhibit UB, which is something that's notoriously hard to do in the general case. Being able to create self-contained units of code that I can reliably (as in compiler-enforced) use with confidence that no UB will pop-up is important. That's presuming that the subsystem does not have any programming errors, of course.

Being able to gate the existence of an API around the conditions that must be met for it to be usable without UB (methods that must be called on an instance), combined with the very simple heuristic of "A class' behavior should be well-defined for any permutation of calls to its public interface." gives me that compiler-enforced no-UB guarantee that I so crave.

That's a BIG deal in a UB-filled language like C++.

-1

u/Loose_Low8543 4d ago

Also you can probably tell I'm not a fan of putting pointers on structures either. Which is why I'm so haphazard to allow zero-init to be the default on my trivial objects.

4

u/ParsingError 4d ago

Yeah except the corollary is that if you're mutating state anywhere, then it's very easy to forget that something in the middle of a series of actions can throw std::bad_alloc and interrupt the series, bail out of the function, and leave things in some kind of half-modified state that breaks its invariants anyway.

If you have error-recoverable paths returning something like a nodiscard status or std::expected that forces you to deal with recoverable errors, then it's harder to forget to handle recovery in places that need it.

3

u/FancySpaceGoat 4d ago

You are correct.

One of the biggest drawback of exceptions is that you need code to be exception-safe across the board. So it's generally not something you should introduce to an existing project.

1

u/Business-Weather-217 3d ago

Agreed. What i do when i get into this kind of trouble is delete ctors and lock down construction to static std::optional<This> Create();

16

u/not_a_novel_account 4d ago

They are objectively faster for the happy path. No branch code evaluated and no BTB slots used at call sites. Exceptions are absolutely necessary for non-local branches when happy path latency is critical and unhappy path latency is irrelevant.

-1

u/Loose_Low8543 4d ago

They're fast in the happy path but still add baggage on the cold path. This is fine for small projects, but can absolutely bloat bigger ones. (Sans the issues with other bloat-y they may already have, i.e RTTI).

13

u/the_poope 4d ago

The point is that exceptions are for exceptional errors. Things that really shouldn't happen in a normal program run. A lot of people and programs are just using them wrong, e.g. for situations where there's a high propability that some condition might not be met.

A well designed program will use mixtures of error handling, each picked depending on the situation.

8

u/not_a_novel_account 4d ago

The cold path is irrelevant for many use cases. If the cold path is "the client dropped the connection" the latency is irrelevant. While the client is live you need latency as close to zero as possible.

"Bloat" needs an objective measurement, if your measurement is happy path latency, branching at callsites is bloat.

-1

u/UndefinedDefined 4d ago

And then "client dropped the connection" is the idea behind DDoS of your service, yeah!

2

u/not_a_novel_account 4d ago

Who says the client is a public connection?

1

u/UndefinedDefined 4d ago • Bravo

This kind of thinking cost companies billions already, so it doesn't need any more comments.

9

u/IyeOnline 4d ago

The huge advantage of exceptions is the automatic propagation up the callstack.

Our codebase uses exceptions for assertions. There is it incredibly useful because you really dont want to introduce return paths for assertion failures. Our product runs individual pipelines and an assertion failure in one should not tear down the entire application. Rather it should tear down that pipeline (and if we wanted to spend the time, we might be able to reduce this even further). This is rather easy if you simply catch the exception (or in our case the coroutine is torn down because of the exception).

Other than that, I there really isnt any outside of dealing with third party libraries.


Getting into your concrete points:

It makes code less clear (I'd argue otherwise)

Both are true. Handling all error propagation manually everywhere is very explicit, but also very cluttered. Conversely, exception error paths are not always clear either - but then again, you are not supposed to be catching so much.

It's standard/idiomatic (Yeah and so is std::auto_ptr)

I dont think I have ever seen anybody argue for exceptions on the grounds that they are specifically idiomatic. Also I dont think auto_ptr was ever idiomatic and it also doesnt h

vector

The problem here is that because you defined a destructor for your type, it does not get a move constructor. Because of that, the resize on emplace back has to do extra work to give you the strong exception guarantee. Now, granted it could have realized that the copy constructor is also trivial, but thats a different story. https://godbolt.org/z/WczMW1v8x

if the thing runs out of memory it's just gonna crash anyways.

I agree. But in a sense its not the fault of exceptions per-se, but rather of their usage and the strong exception guarantee. I would like to think that if this were designed today, the decision would go differently.

-1

u/Loose_Low8543 4d ago

Of course it was a synthetic example to illustrate the accidental "oopsie" from exceptions.

I do agree, if designed today they would've been **very different**, probably for the better.

1

u/Scared_Accident9138 4d ago

How could exceptions be designed differently without turning into a different type of error handling? It seems to me that you just dislike the very parts of how exceptions work

7

u/bert8128 4d ago

I thought that this was interesting in this space https://youtu.be/bY2FlayomlE?is=8DyvuZBe7RoYcdB9 - a cppcon lecture by an embedded dev who thinks exceptions are a good idea.

2

u/Loose_Low8543 4d ago

I can see why that pattern would be useful for embedded where you either a) need to keep a bigger mental model, b) someone else is working on the codebase.

It does still give me off vibes of 'death by a thousand cuts' if not managed well, and it's an extra thing to worry about when writing (as opposed of it being 'less things to worry about'), i.e what if I run out of space faster because of X exceptional code? Esp. the try/catch examples shown, those can paramount quickly.

7

u/JVApen 4d ago

Im used to std::expected which I like more as it tells you the error instead of hiding away.

That said, why use exceptions? Because it makes your code smaller. At CppCon, an interesting keynote was given about that: https://youtu.be/bY2FlayomlE?is=cqR-MK-5IQaxOcVl

0

u/Loose_Low8543 4d ago

I do see `std::expected`, it isn't my cup of tea. I prefer the type itself carrying information (i.e a value which is invalid, the rest is valid). It certainly is a good step for clearer code I'll grant you that, but I personally reserve myself to let the "type speak for itself" sorta.

6

u/JVApen 4d ago

In my experience, types no longer have an invalid state as the instances don't exist in those situations. I much rather see expected<date, parse_error> than having to worry about date containing invalid information. That way, as soon as I have a date, I know that I can use it.

3

u/Plastic_Fig9225 4d ago

 I personally reserve myself to let the "type speak for itself" sorta.

Sounds like you're doing exactly the opposite using magic values. An int doesn't "speak for itself" as to which of its possible values are to be used as actual numbers and which you'd reserve for special meanings. std::expected, otoh, is a type which clearly "speaks for itself", unambiguously denoting and separating values and errors.

4

u/frayien 4d ago

I throw exception as a way to terminate the program with a clear message and stack trace.

Eventually a high level "hypervisor" can catch the error, log that something went horribly wrong with this computation, and go on with the next task.

2

u/Loose_Low8543 4d ago

Isn't that a layer of abstraction that creates cold paths? Whereas you could just set a signal handler for SIGSEGV + print from there?

3

u/frayien 4d ago

That means the worker responsible with starting the task could not run it directly but would have to spin up a new process every time and then watch it and analyze whatever crash report it generated, or better let it generate a core dump and analyze it?

Or should I start the task as normal but save the current state for the signal handler to recover into the continuation of the program?

The more I think about it the more batshit insane it sounds...

Well obviously you have a very different usage of C++ than me, and I fully agree that embed systems should not use exception at all. But my god there are some use cases where exception are so much useful and code size is a complete non-issue...

1

u/Loose_Low8543 4d ago edited 4d ago

If you're terminating a program, a coredump does.

If coredumps are disabled (ulimit -c 0, or slow HDD, or doing fun things with mmap with 500GB coredumps); then manually backtrace the stack or use the std C++ stacktrace but it is NOT signal safe so I would just do it manually.

It's not that hard, if you have EBP/RBP just unwind. Same for arm, mips, sh, ppc, etc, If you're on IA64 you probably already know how to unwind stacks anyways. And so on.

Granted, gets trickier since you have to read yourself to get your own symbols; but that can be solved by just printing the addresses and piping to addr2line.

0 exceptions needed and it's cleaner (in my view of course, I think you have a different view on what counts as cleaner).

23

u/elperroborrachotoo 4d ago

It's the difference between:

FobFroggle f;
int err = FroggleFob(f);
if (err)
   return err;

DoodleResult dr;
err = Snackdoodle(f.snack, dr);
if (err)
   return err;

result = dr.wrapper;
return 0;

vs. the ability to write

return SnackDoodle(FroggleFob({}).snack).wrapper;

(Granted, there's some often-nicer patterns, and std::expected sits kind of inbetween, but...)

The idea of exceptions is to expose the happy path. Move the error handling out of the way. We want to Doodle the snack of a freshly froggled fob, and return its wrapper.

The compactness is a benefit ("more payload on screen"), as is the "can't continue after error (except loudly)", but the key is the separation of normal vs. exceptional.


We pay a price, though: there is a "hidden" control flow now, that requires "good practice" in resource management and side effects. It requires to make a call what actually is exceptional (and sometimes, only the caller knows).

As has been noted, recognizing incorrect exception-based code is harder than incorrect error-code-based code. Which is easy to demonstrate on a small scale - but we should judge it on large-scale projects. Millions of eyes didn't catch the easily visible goto fail.

To add, in most languages, exceptions automatically provide more diagnostic context (only mandated recently in C++).

10

u/mredding 4d ago

Exceptions are discouraged in embedded systems, so I'm not going to fault you for not using them in that environment. I'm not even going to try to suggest opportunities to use them because it's so idiomatic to exclude them, there's no point in trying.

In application software, where resources tend to be more abundant, exceptions ARE effectively free. You need an incredibly tight critical path if you're measuring exception paths in it. But if your process is going to be interrupted by the scheduler, then WHAT critical path do you think you're even talking about? And in trading systems - and I can speak from personal experience, you're either fast - meaning you're entirely on the NIC FPGA, or you're not fast at all and it doesn't fucking matter.

So exceptions are nice in a few instances. They're common in constructors and operators, IF they can fail. Classes enforce an invariant, and that invariant MUST be established by the end of the initializer list, and you must implement this yourself by convention and discipline because the language can't enforce it for you. You can suspend the invariant in the body, but it must be reestablished before the body returns.

Why? RAII. There is no separate init like you might in C. A class instance is never observed by client code to be in an indeterminate, intermediate, invalid state. It is either born whole or it is aborted.

If it were me, I'd go out of my way to make sure operators can never fail, but if they must exist and can - then exceptions. It's the only way to indicate such failures without embedding fail state and checks into the object, and if you do THAT, now you have to check THAT, and I can't force you to write safe code. You can't ignore my exception.

And from that conclusion, I can say exception capable code becomes easier to use correctly, harder to use incorrectly. You would have to go out of your way to fire that foot gun.

Exceptions allow me to very cleanly throw back to an exception handler, which may be on the far end of the stack. Now I don't have to manually code all the back propagation through the stack. An IO handler can throw that the socket is closed, and way further back is the retry loop that establishes a connection down an alternate path.

You need to write exception aware code. You need to factor this into the construction. If a socket closes, what does that mean for the context, the buffers, the mid-IO? These are all the same problems you have to deal with anyway, just now in a different way than you're used to. It's just a different style of programming.

Exceptions are a tool, and I'd say a bit of a skill, too. You're not going to use a tool you're not good at using, but if you see a master at work, it can be very impressive indeed. The whole point of exceptions is to make code SIMPLER. If you're not reducing piles of conditional error handling code with exceptions with a couple throws, a couple catches, then something is wrong. But GOOD exception code is all happy path unconditional code with just a couple throws out of the way. It's really crisp to see clean exception code. I know you've seen how error handling can dominate the body of a function, where the actual business logic is the smallest, most insignificant part, lost in a sea of formatting error messaging or whatever else. That's just another world of suck we should all endeavor to avoid, as well, and maybe an exception is the proper tool for that job.

5

u/smallstepforman 4d ago

It is the invisible code paths that annoy developers. If throwing functions had the keyword "throws" in the signature, and if the compiler enforced catching these exceptions, then IMHO most devs would find exceptions useful. Right now, it is invisible and we have no guarantee all our code paths are exercised and tested. The C++ attribute "nothrow" is the opposite of what we need.

Also, historically exceptions were designed to simplify deeply chained scope exit. A useful concept but historically very unpractically. The other use case is memory allocation failure, but with overcommit, even memory failures no longer raise exceptions on leading platforms.

Due to legacy codebases we cannot easily reverse this situation we're in, so a half the community either ignore exceptions or forbid it. Wonderful <rolls eyes>

2

u/Plastic_Fig9225 4d ago edited 4d ago

Yeah, Java does it better by a) providing a framework for and hierarchy of exception types and b) providing the Exception base class for exceptions which must be either handled or declared, and Throwable / RuntimeException which can be used to sneakily bypass the mechanism. And you cannot throw just any value of any type you like. - It's not perfect because the decision of how "important" (enforcement of) handling of a specific exception is often cannot be made universal inside a library's code, but it's still not a bad approach.

4

u/conundorum 4d ago

Remember that not everyone has to work within the same restrictions as you. Exceptions are perfectly fine if you don't need to fight your way through the Dungeon of Horrors with nothing but a butter knife for even a single spare byte or cycle, and you're designing for a system that's so underutilised that it needs an idle process to waste the leftover resources. (This doesn't mean that they should be abused and bloated just for the sake of bloat, just that "I need to worry about functions' byte alignment and can't spare the cycles for a system call" is a very different environment with very different rules than your standard Windows or Linux system.)

Assuming that they're used correctly1, the point of exceptions is threefold:

  1. They let us move the error-checking out of the main code path, at least for uncommon errors. C-style error return codes are well-understood and easy to write, but they waste cycles on branch checks; we can lessen the waste by using a jump table with either massive case blocks or force-inlined functions, but we're still spending time on the check & jump themselves. Especially when the error is caused by code that we have no control over, such as a library call. Proper use of exceptions lets us isolate the jump to only paths where a major error is known to have occured, potentially allowing us to shrink (or sometimes even remove) the return code jump table. Thus, they function as a form of optimisation, by moving the bulk of the error-handling onto an infrequent side path and leaving the main path free of unnecessary checks. (Either completely check-free, or whittled down to only the ones that are actually necessary.)
  2. They help to indicate what failures/errors are and aren't expected, or are and aren't reasonable. In some situations, some types of failure are expectable, and that's okay. Sets of unique data fail to add an element that's already in the set; failure is the desired result, because elements are expected to be unique. File I/O fails to open nonexistent files in input mode; failure is the desired result, because the files don't exist. Unsorted data may fail to be in the desired order; this is a plausible result, because the elements weren't sorted. Random atoms fail to undergo spontaneous nuclear fission or emit deadly radiation for no reason; failure is the desired result, because I'd hate for my computer to turn into a nuke. In all four cases, either success or failure are equally viable, and/or failure is preferred over success. Thus, these results are treated as normal.

Meanwhile, if a set of unique data fails to add an element that's not in the set, it throws an exception. Many I/O systems will throw an exception if a file that's known to be openable fails to open, because it suggests a deeper underlying issue with the file system. Sorted data being out of order might throw an exception, because it indicates unsanctioned reordering and/or a flaw in the sorting algorithm. And the elements in the sea of tranquility are considered exceptional because they should be radioactive, but aren't. These results are exceptions because we know that success is the expected and reasonable result.

Thus, we can use exceptions to mark a specific type of failure as "unexpected" or "unreasonable", and by extension indicate that all non-exception failures are reasonable and/or expected. This attaches more meaning to error-checking: When we see return value checks in exception-based code, we know that there are at least two distinct valid results, because all of the invalid results have already been filtered out.

Think about it like fish. A two-eyed fish is normal. A one-eyed fish is an error. A two-fished eye is an exception. Fish normally have two eyes, and it's plausible that one might become damaged or lost, but it's normally impossible for anything to have a conjoined eyeball. (And a three-eyed fish is a SimpsonsException, but that's neither here nor there.) 3. Proper usage of noexcept lets us indicate where serious errors can never occur. When we declare a function to be noexcept, we're saying that the function itself will never throw an exception (and by extension, never encounter an unexpected or unreasonable error/failure), no matter what input we feed it. All possible inputs will result in either success or an "expected"/"reasonable" fail state. This allows us to use it with impugnity, even in otherwise-unsafe conditions, because we know those conditions can't cause it to fail. And more importantly, it allows us to extend that safety outwards; any function that only calls noexcept functions and only performs noexcept operations is noexcept itself, because it lacks any potential exception-worthy-failure points. And that's really useful, because it both allows us to write safer code, and allows the compiler to perform more aggressive optimisations that would be likely to break less iron-clad code.

Thus, the promise of noexceptness can free up memory and cycles that would otherwise be wasted on safety code, and also allows the compiler to omit the exception path entirely until we return to exception-capable code.

(This is also why exceptions in a noexcept segment force a std::terminate() call: The noexcept code itself cannot cause an exception, therefore something outside of the code base is responsible. And that means that the environment itself is too unstable to expect valid results. If you get an exception in a noexcept file-opening routine, then there's a very real chance that the drive itself has been physically removed from the system, which renders all file I/O impossible by definition; the only reasonable thing to do is to shut the program down, so the system can salvage whatever resources it has left and try to return to a workable state.)

Overall, for most programmers, exceptions can provide many significant benefits if they're used correctly. Especially if the compiler doesn't force an allocation or other costly resource usage when they're thrown (from what I understand, MSVC is a bit better about this than gcc, but I don't know where other compilers stand). Your use case doesn't reflect the norm; it would be unwise to optimise for your niche case and pessimise for the common case.

Not to be rude, but if it were me, I would consider your exception-removing edits to be sabotage, and revert or reject them with a comment that valid edits will only be accepted if you stop trying to redesign everyone else's code to only work on your system. If you continued to try to remove exceptions, I'd have no choice but to ban you, because you're the one doing the backstabbing. And that's not ideal for anyone, really. So, I'd suggest that while you continue to write exceptionless code for your own environment, you try to understand that many other environments are much friendlier to exceptions than yours is.

Instead of trying to force your rules on everyone else, prefer to follow the code's current style; if you have a problem with it, then bring it before the library owners and let them make the decision. It's not your choice to make.

(Also, there are specific situations where all errors are unreasonable, and/or create an unreasonable environment. Things like, say, constructor or destructor calls, where an error can result in half-built objects occupying phantom memory that the system both doesn't know is allocated and can't deallocate. In this situation, we outright need exceptions to be able to jump in and fix things while we're still "inside" the construction/destruction process, before the memory is leaked beyond our ability to recover.)


1: Exceptions are exceptional; they're big deals, not regular fail cases. We can use them for cases where something went "horribly wrong" [e.g., when opening a file for input, "file opened" is success, "file not opened" is failure, and "file does not exist" might be a failure or an error or an exception, and "filesystem does not exist" is an exception], or when an operation has an abnormal and otherwise-impossible result [e.g., 1 + 1 = 2 is normal, 1 + 1 = 3 is an error, and 1+1 = Batman is an exception`]. You shouldn't need to worry about whether the filesystem disappeared out from underneath you, or whether your addition result is going to go fight crime at night, so we put then on the "exception path" to keep them out of the reasonable result paths. [The main differentiator is that failures are reasonable, and exceptions are not. It's valid for a file to not exist, and it's valid for someone to screw up math; the results are undesired, but not impossible.]

2

u/TryToHelpPeople 3d ago

Most people misunderstand exceptions.

Throw an exception when you encounter a condition you cannot proceed from, which must be handled, and you can’t decide at that point how to handle it (usually this is in library code).

Catch an exception when the scope you’re working on can handle something which has gone wrong (usually in user code).

It sounds like your embedded team is small and can design around anything that happens.

1

u/Kadabrium 4d ago

inplace_vector?

1

u/fortsnek274 4d ago

I develop small embedded shit and such

Well, there you go. That's the sphere of people doing things differently from desktop applications.

4

u/the_poope 4d ago

From OP's comments I get the idea they are an electronics engineer working on a home made Tamagochi as a hobby project in their garage. They learned C 30 years ago and are still using C++ as C with classes. Their programs are like 1000 lines of code that follows an almost linear flow and makes some LEDs blink. That's it. They fail to see the utility of many modern C++ features because they have never worked on a large complex project.

Then they ask "Why use all these stupidly complex and fancy features?". It's a bit like asking why to use an industrial bread factory with conveyor belts, robots and advanced machine to bake bread when you can do it at home with a bowl, water, flour, yeast and an oven.

1

u/Plastic_Fig9225 4d ago

drop using the libc/libc++ and do [...] a syscall for a big mmap and then manually allocate memory

Syscalls, mmap... - OP seems to be actually using a somewhat heavy full operating system (Linux?). The way he presents the "issue" indicates that he may not be quite aware of when optimization is warranted or why you may not need to re-invent wheels when you feel that one naive approach may not be optimal.

2

u/the_poope 4d ago

Maybe they want to run the Tamagochi at one million FPS?

1

u/Plastic_Fig9225 4d ago

With one malloc call per pixel rendered.

1

u/Right-Edge-5712 4d ago

For practical non-theory reasons, exceptions are buried so deep in documentation that you don’t know if exceptions will be triggered

1

u/iku_19 4d ago

For me, and this is strictly just me I think, exceptions are usually reserved for the first step removed from something catastrophic and unrecoverable. Proper error handling with error states (or std::optional, std::expected, the Option<>/Result<> we have at home) allows for way neater communication of issues in my opinion.

The issue becomes bubbling the error states up. Exceptions just let you rethrow it until eventually something "catches all the shit" but you have to actively handle each error state. This benefit is also why they're so dangerous. Something may inadvertently throw a random exception you didn't realize about (It's why I appreciate Java requiring each function to list what it could throw, and I wish more languages did that.)

I personally prefer just using error states over exceptions since it feels more deterministic. Handling error states in constructors is also ugly, so I see the benefit there.

1

u/Discordbothost 3d ago

The size cost can show up in unwind tables and cleanup code even when the parser never throws. For your embedded target, I'd compare the final linker maps with exceptions on and off at the same optimization level. That'll tell you how much flash the two builds actually use and which sections account for the difference.

1

u/Individual_Cover8629 3d ago

i learned so much from this post

1

u/Independent_Art_6676 3d ago

I will answer a little differently.. small embedded is not expected to follow the patterns used for multimillion line of code major projects designed for PC use. The programs are smaller, often VERY small, and a great deal of modern C++ is to make large projects easier to handle, from errors to organization. To me that means that you are probably right: there are things in c++ you won't need or use much, if at all, in your line of work. It may be very well that you don't need to learn exceptions or use them, but I would at least know they exist (you do) and how to use them a little (you do) so you can look it up and apply it if you find yourself working on a desktop program or needing it for some specialized or larger capability embedded. Some embedded systems are full PC capable and for those you might use them. If you don't need them, or use them, its probably OK for you if your employer is fine with it.

1

u/Cross_22 3d ago

Just like you I am doing embedded and low-level programming and -fno-exceptions is the default.

I appreciate the way that exceptions are implemented in Java where handling them is mandatory and they basically become variant return codes. The C++ way of something might be throwing something down the call stack.. who knows.. good luck finding out! Is not something I consider worthwhile to add to my codebase. Of course if there's an existing codebase I am not going to rip it out either.

1

u/Neither_Berry_100 3d ago

I hardly use them. One case where my current game can throw is in reading messages over the network. It reads in messages by size and processes them. The processing may vary how much is read. If they hack and send bad data it can read outside of bounds of the data. I read the entire thing before processing it. I wrap it in a try block. If the user hacks the only thing that happens is their message is voided. It achieves nothing. So they won't do it. And the code is perfect and will never do this unless the user is hacking and purposely sending bad data.

1

u/PipingSnail 21h ago

I try to avoid exceptions. The thing I hate is an exception being thrown from code you don't expect to throw and it kills the program. And typically in these situations it's people treating perfectly normal conditions as exceptions instead of error conditions.

Examples are file not found, access denied, url not found, data transfer errors.

None of these are worthy of an exception but I've had to wrap code in exception handlers because someone coded a library to throw exceptions rather than do the right thing and return an error code.

The clue is in the name. Exceptions are for exceptional conditions.

Furthermore, if an exception kills your programme that is a shockingly bad UX for the client of your programme whether that client is a human or another programme. Programmes should fail gracefully and in a controlled way. By throwing exceptions left right and centre you're making that less likely to happen.

Report errors early and frequently with detailed error codes, not catch all codes. This allows far superior error handling. K.

Keep exceptions for the few cases where there is no other option for dealing with it (constructors, destructors, stack corruptions and so forth).

And SEH for when you need to wade into uncharted territory. Most of you won't need that, but it's useful if you're working on code that needs to inspect data that may not be what it claims to be,or may contain undocumented variants of an original format. PE files, minidumps...

1

u/No_Mango5042 7h ago

The purpose of exceptions is to force you to deal with errors. Secondary, it guarantees that objects are always in a valid state, for however you define valid. If you write your code properly it will be robust to errors without the clutter of error checking everywhere. Exceptions are more helpful in scenarios where you want to recover from errors rather than stopping the world, e.g. an IO error part way through reading a file.

1

u/einpoklum 4d ago

You sound to me like the person about which they coined the phrase: "Premature optimization is the root of all evil".

I also drop using the libc/libc++ and do syscalls raw because I can't stand the overhead

Are you sure your problem with them isn't more in principal than with your actual performance needs?

And no, noexcept also sucks because it just wraps shit around {} with std::terminate(), which is dumb (atleast on MSVC, but whatever).

Don't do things which can throw exceptions within noexcept code. You want to parse JSON? Great; allocate a slab of memory beforehand for each thread, and let them go wild. no races, no out-of-memory, no system calls, no glibc calls... you just have to (maybe) trim and (maybe) combine after the individual threads' work is done.

-3

u/UndefinedDefined 4d ago

I don't use them, never will. Sane codebases don't use them, look at Chromium, for example.

I think the biggest problem is error separation and drastically different performance of happy vs unhappy path. Deciding what is exceptional can get very personal, and arguing about this in PRs can divide. I have seen that, no thanks!

And then there is control flow clarity - when using error codes or some kind of `expected` or `value_or` or `maybe`, or whatever name you use, the control flow of handling errors is very clear and each error path is easy to review (and not just that - you can trigger the error and get 100% branch coverage in tests, if required). But this is impossible with exceptions. Writing an exception-safe code in code-bases that rely on exceptions is very difficult, anything can throw, explicit try{} catch{} blocks just to rollback states and so... I would never design an architecture like this.

I know many would not agree with this, but this is what I generally saw in proprietary code. Everything that mattered didn't use exceptions, but UI stuff or something irrelevant was free to use them for whatever needed.