Exception Handling in C++

This page might seem like it duplicates some of what we have just seen, but it is valuable because it gives a different perspective on the topic. Read chapter 1 on pages 15-60.

Standard exceptions

When not to use exception specifications

If you peruse the function declarations throughout the Standard C++ library, you'll find that not a single exception specification occurs anywhere! Although this might seem strange, there is a good reason for this seeming incongruity: the library consists mainly of templates, and you never know what a generic type or function might do. For example, suppose you are developing a generic stack template and attempt to affix an exception specification to your pop function, like this:

T pop() throw(logic_error);

Since the only error you anticipate is a stack underflow, you might think it's safe to specify a logic_error or some other appropriate exception type. But type T's copy constructor could throw an exception. Then unexpected( ) would be called, and your program would terminate. You can't make unsupportable guarantees. If you don't know what exceptions might occur, don't use exception specifications. That's why template classes, which constitute the majority of the Standard C++ library, do not use exception specifications ­– they specify the exceptions they know about in documentation and leave the rest to you. Exception specifications are mainly for non-template classes.