Exceptions
In C every call had to be checked for error values - which could double the code size. C++ exceptions are an alternative to traditional techniques when they are insufficient, inelegant, and error-prone. Three keywords are involved
- try
- - specifies an area of code where exceptions will operate
- catch
- - deals with the exceptional situation produced in the previous try clause.
- throw
- - causes an exceptional situation
When an exception is 'thrown' it will be 'caught' by the local ``catch'' clause if one exists, otherwise it will be passed up through the call hierarchy until a suitable catch clause is found. The default response to an exception is to terminate.
There are many types of exception - they form a class hierarchy of their own. Here just a few will be introduced.
try { // code } // catch a standard exception catch(std:exception& e){ // order of the catch clauses matters; they're tried // in the given order } // catch all the other types catch(...) { // cleanup throw; // throw the exception up the hierarchy }
Here's an example that sooner or later will produce an exception.
try{ for(;;) new char[10000]; } catch(bad_alloc) { cerr << "No memory left"; }
An exception example is online.
You can override the routine that handles problems encountered by the new operator
set_new_handler(&my_new_handler);
For safety, you can declare which exceptions a function should be able to throw
int f() throw (std::bad_alloc) // f may only throw bad_alloc
A useful exception is
out_of_range
(header <stdexcept>
), which is thrown by at() and by
bitset<>::operator[]()
.
Exception handling code can slow a program down even when no exceptions happen. The code size will also increase.