r/cpp_questions • u/Loose_Low8543 • 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).
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).
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.
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:
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.
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
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
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.
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.
7
u/JVApen 4d ago
Im used to
std::expectedwhich 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
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.
23
u/elperroborrachotoo 4d ago
It's the difference between:
vs. the ability to write
(Granted, there's some often-nicer patterns, and
std::expectedsits 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
initlike 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>
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:
caseblocks 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.)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 aSimpsonsException, but that's neither here nor there.)3. Proper usage ofnoexceptlets us indicate where serious errors can never occur. When we declare a function to benoexcept, 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 callsnoexceptfunctions and only performsnoexceptoperations isnoexceptitself, 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
noexceptsegment force astd::terminate()call: Thenoexceptcode 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 anoexceptfile-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 = 2is normal,1 + 1 = 3is an error, and1+1 = Batmanis 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
Well, there you go. That's the sphere of people doing things differently from desktop applications.
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".
Are you sure your problem with them isn't more in principal than with your actual performance needs?
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.