Re: Throwing Exceptions
- From: Peter Ammon <gershwin@xxxxxxxxxxxxxxx>
- Date: Sat, 23 Apr 2005 17:17:39 -0700
Gregory L. Hansen wrote:
Do people often use exceptions by choice in C++?
No. Here's lots of reasons why.
1) Exceptions are sporadically used by 3rd party libraries and frameworks. With the exception of the STL and probably Boost, I haven't seen any library or third party framework that is designed to take advantage of exceptions consistently.
2) C++ permits code to throw exceptions without declaring them; exception safety isn't enforced by the compiler as strongly as in, say, Java.
3) The STL isn't guaranteed exception-safe in lots of important places, like containers.
4) C++ compilers do not consistently implement exceptions. For example, last I checked, Visual C++ will return NULL instead of throwing a bad_alloc exception (as required by the standard) if new fails. This makes exceptions more difficult to include in portable code.
5) C++ exceptions are not widely understood. This vicious cycle means that writing C++ code with exceptions reduces the pool of programmers who can maintain it.
6) C++ exceptions on most implementations cause a performance hit, even if no exception is thrown.
7) C++ exceptions are extraordinarily difficult to reason about. For example, consider the seemingly simple problem, as posed by Herb Sutter (who sits on the C++ standard committee), of writing an exception safe stack.
http://www.gotw.ca/gotw/008.htm
His solution turned out to be 1) not entirely correct and 2) not compileable by any compiler he had. Nasty!
I can't think of much I'd do with them that I couldn't do with return values
Some people say that exceptions are better than return values because return values indicating errors are often ignored, leading to undefined behavior, and exceptions at least "force something to happen." Others disagree; this is one of those religous issues where you should make up your own mind.
Exceptions can also be used for flow control, as seen in other responses to your post.
, but they do seem to complicate things by providing a second error-checking procedure that some functions or classes will use but others won't.
Exceptions are part of the specification of a class or function, and need to be considered during the design instead of tacked on afterwards. You're right that they complicate things and are less useful if not used consistently, but they let you indicate errors much more cleanly than many of the hacks in wide use (like errno).
-Peter
-- Pull out a splinter to reply. .
- Follow-Ups:
- Re: Throwing Exceptions
- From: Gregory L. Hansen
- Re: Throwing Exceptions
- From: Serge Skorokhodov (216716244)
- Re: Throwing Exceptions
- References:
- Throwing Exceptions
- From: Gregory L. Hansen
- Throwing Exceptions
- Prev by Date: copyright your code
- Next by Date: Re: Throwing Exceptions
- Previous by thread: Re: Throwing Exceptions
- Next by thread: Re: Throwing Exceptions
- Index(es):
Relevant Pages
|