I have been programming in C++ on and off for about 5 years, why have I never seen exceptions used other than examples for examples sake?
11 Answers
Observation bias at work here.
A significant fraction of C++ code is for systems programming and embedded systems. (After all, C++ is just one of many options for applications programming, and many of the alternatives have fancier RAD environments, but in systems work, it's often the highest level language for which a compiler is available, by a wide margin). And most embedded systems as well as a significant chunk of systems development work have constraints that rule out exceptions.
If because of your focus, you tend to search out this sort of code, it's entirely possible that the C++ code you've seen doesn't use exceptions.
That doesn't mean that there isn't C++ code using exceptions -- there is, and a lot of it. It may just not appear in code designed to solve problems that are interesting to you.

- 277,958
- 43
- 419
- 720
-
@J T: I don't mean he's looking for "code that doesn't use exceptions", I mean he's likely looking for "code for doing X in an embedded system", and a consequence of embedded systems not using exceptions is that he finds code without exceptions. – Ben Voigt Mar 24 '11 at 23:29
-
1@Ben: right, I'm just saying, "What if he isn't working in embedded systems?". Since his original question never mentions embedded systems (and the same question can be applied to the non-embedded world). – J T Mar 24 '11 at 23:31
-
1@J T: I'm not saying tm1rbrt's interests are embedded systems. It could be, [as Marino points out](http://stackoverflow.com/questions/5426708/why-are-exceptions-so-rarely-used-in-c/5426805#5426805), Windows DLLs, since exception crossing DLL boundaries cause intense pain. One way or another, his interests are creating a bias toward not seeing code with exceptions in it, because it certainly isn't true that "serious C++ code using exceptions is scarce", as tm1rbrt appears to have concluded (looking at the question title). – Ben Voigt Mar 25 '11 at 00:30
-
@Ben: Well, if the answer to the poster's question is indeed that "serious C++ code using exceptions is scarce" is FALSE, then you could have just written that. Making a claim that he is observationally biased requires showing some mechanism that would bias him thus. In fact, without such a mechanism, I could just as easily make the argument that perhaps you are observationally biased because of the environment you're working in - and that serious code does often lack exceptions where exceptions are due. I'm just trying to make the point, that we can't just dismiss his claim without a reason. – J T Mar 25 '11 at 02:53
-
@J T: I'm not going to disagree that "serious code does often lack exceptions when they would be useful"... there's an awful lot of C++ code running around, which means a lot appropriately avoiding exceptions, a lot appropriately using exceptions, a lot inappropriately avoiding exceptions, and a lot badly using exceptions (people who badly use exceptions rarely are working in an environment where they're inappropriate). It isn't difficult to find plenty of C++ code that uses exceptions (e.g. boost). What other explanation can you provide for thinking there isn't, except observational bias? – Ben Voigt Mar 25 '11 at 03:25
-
@J T: Every other answer here, including yours, explains why there is a lot of C++ code without exceptions. None actually address the question of whether C++ code with exceptions is "rare" as the title presupposes. – Ben Voigt Mar 25 '11 at 03:26
Exceptions are a fairly late addition to the language, so I believe many C++ developers have never learnt to use them properly, and may feel more at ease using traditional (C style) error handling techniques.
I personally think they are indispensable in handling constructor failures (that is the foremost reason they were added to C++ after all), but they also require the correct use of other advanced (YMMV) techniques like RAII or smart pointers to avoid resource leaks.

- 114,404
- 31
- 268
- 329
-
9And few libraries use them - because nobody uses them - because few libraries use them .... – Martin Beckett Mar 24 '11 at 23:18
-
4constructors are a good one, but operators are another case where exceptions are extremely useful: there's often no simple, direct way to return an error code and know that the user won't ignore it. – Tony Delroy Mar 25 '11 at 05:34
I have been programming in C++ on and off for about 5 years, why have I never seen exceptions used other than examples for examples sake?
I'm very curious about this. I'm very curious about this since in 1996. Sometime I think in 1996 C++ Exception Handling revolutionized the way I'm writing software. I remember that I was reading about C++ Exception handling and I immediately understood the implications. Within minutes I was testing what happens, if an exception is thrown from a constructor. Compilers for UNIX were not ready for C++ Exception Handling until G++ 3.0 I think (whe was this?). Destructors were called for not constructed memory locations (on the stack) (in case of some exception was thrown). Destructors were not called for successful constructed objects (on the stack) (in case of some exception was thrown). delete was not called in case of an object created with new threw an exception from the constructor. Compilers for Windows and OS/2 were ready in 1996/1997. They worked. I remember Borland C++ for OS/2 and IBM CSet2 and Windows Visual C++.
Finally there was a method to abort construction of an object. Finally one could allocate an object inside a constructor AND rely on the successful construction of this object in some other constructor. Somehow I found out about all the rules. Not from books! Years later books came out, claiming that C++ Exception Handling is a good way to catch array-out-of-bounds error or other problems for which I never stopped using assert. Finally there was an easy method to provide the caller with complex information about some error without relying on stderr. Finally one did not need to debug some complex piece of software to find out, what was failing.
I cannot take people seriously, which are not using C++ Exception Handling. It is impossible to check every fallible call. It is impossible to reach the same level of quality of software without using C++ Exception Handling. Why are such people still hired? Why are there still platforms, which do not provide C++ Exception Handling. I would never consider writing software for such a platform, in the same way I would refuse writing a complex application in assembly code.

- 1,048,767
- 296
- 4,058
- 3,343
Curious. I work in C++ regularly, and it's been at least ten years since I've seen any C++ code which doesn't use exceptions. Anytime you have to propagate an error up a significant number of stack frames, you use an exception.

- 150,581
- 18
- 184
- 329
Several reasons come to mind:
- Exceptions shouldn't be very visible, since they are designed to be thrown deep in the bowels of a library and caught somewhere high up in the call stack (even as high as
main()
). - They are intended to signal exceptional (i.e., rare and unexpected) faults. For example, failure to open a file isn't particularly exceptional. So, by default, the iostream library doesn't throw an exception when it fails to open a file.
- Exceptions are very expensive to throw, which encourages adherence to the design intent.
- C++ libraries that throw exceptions don't interface easily with C programs.

- 181,030
- 38
- 327
- 365
-
7"Exceptions are very expensive to throw" - how expensive? I think last time I tried to profile this, I got a figure of about 10us per throw/catch across multiple stack levels, as the excess cost above backing out of the call stack with `return`. Leaving aside realtime systems, if enough "rare and unexpected" faults are happening per second that it's possible to detect this overhead, your program has more important problems to fix than performance ;-) – Steve Jessop Mar 24 '11 at 23:33
-
Ah, here's the test I used. The timing figures were without optimization, so not terribly meaningful, since the point was just to demonstrate code that could be run on any chosen machine to get an idea of cost. In a tight loop worked out to 13us throwing a short "distance", and 1.5us per level of stack throwing a long "distance". http://stackoverflow.com/questions/1018800/performance-of-c0x-exceptions/1019020#1019020. Still, the *belief* that exceptions are expensive might nevertheless affect coding styles. – Steve Jessop Mar 24 '11 at 23:42
-
2@Steve Jessop: Interestingly, your test if compiled with `g++ -O3` on a macbook pro (Core 2 Duo 2.53GHz), and then timed for a few times shows a high consistency of `0.002` seconds in the `return` case and `0.416` seconds in the `throw` version. I was surprised when you commented that there is not a much higher cost for exceptions, because we banned them from our inner loops at work after we saw the impact they had... Then again, outside of the core, the system does use exceptions. – David Rodríguez - dribeas Mar 24 '11 at 23:57
-
@dribeas: Hmm, that's 2us total runtime per repetition for the "return" case, or 2ns per stack level. This suggests to me that a more robust `SpaceWaster` is required at that optimization level, since 5 clock cycles each isn't very plausible to actually create the objects and write the decremented count into each. I suspect the whole test has been optimized away in that case. But sure, in tight loops you can spot the difference, which is why I only say that if they're "rare", they won't also add up to "very expensive". Normal hotspot profiling rules apply. – Steve Jessop Mar 25 '11 at 00:04
-
... and if the presence of exception-using code is impeding the optimizer in its efforts to speed up your real-life tight loops, then *that's* a good argument for banning them irrespective of what (if anything) it costs to actually throw one. – Steve Jessop Mar 25 '11 at 00:13
-
2@Steve: Guess your optimizer is no good, or you're testing with a toy project that isn't big enough. One well-known optimization is to separate exception handlers from fast-path code, in order to improve code locality and therefore i-cache hit rates. As a bonus, the working set is smaller. With this optimization, throwing an exception may cause a page fault, as the OS loads the associated code. But with a toy benchmark, both hot and cold code probably fit in a single page. And now you're talking exception handling cost of several milliseconds. – Ben Voigt Mar 25 '11 at 00:34
-
OTOH, a really good optimizer could do the same thing with conventional error-handling code. – Ben Voigt Mar 25 '11 at 00:36
-
+1 for @David's testing results and @Ben's page-fault comments. 10 μs *is* very expensive compared to a few nanoseconds to handle a conventional error return code, and the impact is easily detectable in real-world programs. – Marcelo Cantos Mar 25 '11 at 01:33
-
@Marcelo: The testing is with Steve's code, so I am not to blame/appraise for that. Also consider that the numbers are quite bogus, on the one side due to Ben's comment, but also because I did not analyze the output of the compiler (assembler), and that can mean that the two code paths are completely different, i.e. the measurement does not take into account the actual exceptions but rather some other effect (the compiler might have removed a big chunk of code in one case, then again in real code the compiler might or not be able to do it...) That is why you have to measure everytime! – David Rodríguez - dribeas Mar 25 '11 at 08:23
-
7@Marcelo - We are comparing 10us that happens rarely to "a few" ns that happens always. How can we tell upfront what is most expensive? Not having to check return codes always, might make your hot path faster. – Bo Persson Mar 25 '11 at 08:36
-
@Bo: The point I originally made was that exceptions are expensive to throw, and thus should be thrown sparingly. Do you disagree with that claim? – Marcelo Cantos Mar 28 '11 at 02:04
-
@Marcelo - I agree that exceptions should be thrown sparingly, because they signal exceptional cases that cannot be handled locally. Not that checking return codes everywhere is a time saver in comparison. – Bo Persson Mar 28 '11 at 04:15
-
-
1+1 for "they are designed to be thrown deep in the bowels of a library": my C++ code rarely throws exceptions anywhere else. But it is fairly common for my code to catch and re-throw exceptions to ensure exception safety. – Raedwald Mar 31 '11 at 12:22
Exceptions are too advance for beginners so these are not always shown in the examples, especially on books.

- 21
- 2
I could say the same thing and it would not be biased a lot, if i define that this is true for a Microsoft world and RAD.
I think it is because today you don't use C++ programs per se but rather a mixture of high level language using C++ libraries. And often you have a managed-unmanaged boundary.
Throwing and catching exception through this boundary is like lighting a firecracker in you ass :) - [read mem leak or worse]
Moreover if you use COM objects you have to use COM exceptions, so the usage of standard C++ exception must reside internally in a often small library. In small libraries you dont have a need to use exceptions.

- 7,318
- 1
- 31
- 61
Because there is a huge discrepancy between "real-world" code and "text-book" code.
I work in a "large" software company and can honestly tell you that the stuff you see in production follows nearly 0% of the good practices you read about in good books.
Take Scott Meyers' Effective C++ book as an example. Should be a copy on every software engineer's desk, from east coast, to west.

- 4,946
- 5
- 28
- 38
-
1Although it should be uncommon to `throw` an exception, it should be reasonably common to `catch` and re-`throw` an exception to ensure exception safety (to roll-back a change). As this is in my experience rarely done, I suspect that vast amounts of production C++ code are not exception safe. See http://stackoverflow.com/questions/1853243/c-do-you-really-write-exception-safe-code for more information. – Raedwald Mar 31 '11 at 12:38
I'm speaking of desktop applications for Windows. In my observation (YMMV too), earlier phase of the development probably until initial releases. Many developers doesn't think of exceptions early on. That is why there are few codes with exception handling but if you had like 2 or 3 releases already or if your on maintenance phase, exceptions are being considered due to various deployment environments through error reports from customers.

- 174
- 3
- 8
Exemptions are not used in examples because it is rarely the focus of many of the questions or something you want to know in the first place.

- 174
- 3
- 8
Several reasons come to mind:
- Exceptions shouldn't be very visible, since they are designed to be thrown deep in the bowels of a library and caught somewhere high up in the call stack (even as high as main()).
I don't know what you mean with "Exceptions shouldn't be very visible". But I agree that catch-blocks should be rare -- and they are usually in main.
- They are intended to signal exceptional (i.e., rare and unexpected) faults. For example, failure to open a file isn't particularly exceptional. So, by default, the iostream library doesn't throw an exception when it fails to open a file.
that the iostream library does not throw exceptions makes it kind of unuseable. Hiding errors from the caller! This is so C like.
- Exceptions are very expensive to throw, which encourages adherence to the design intent.
Usually Exceptions are for system calls failing. Since writing to a file or opening a file is not really inexpensive, one would not care about Exceptions being expensive. Also having to check for success is more expensive than using C++ Exception Handling. Usually one would not create a try-catch block inside a time critical part of code.
- C++ libraries that throw exceptions don't interface easily with C programs.
What is C? Ah yes -- I remember -- something I gave up around 1996. Remember Turbo Pascal?