To implement an exception handler, do these basic tasks:
When a function is called by many other functions, code it so that an exception is thrown whenever an error is detected. The throw expression throws an object. This object is used to identify the types of exceptions and to pass specific information about the exception that has been thrown.
Use the try statement in a client program to anticipate exceptions. Enclose function calls that might produce an exception in a try block.
Code one or more catch blocks immediately after the try block. Each catch block identifies what type or class of objects it is capable of catching. When an object is thrown by the exception, this is what takes place:
If the object thrown by the exception matches the type of the catch expression, control passes to that catch block.
If the object thrown by the exception does not match the first catch block, subsequent catch blocks are searched for a matching type.
If try blocks are nested, and there is no match, control passes from the innermost catch block to the nearest catch block surrounding the try block.
If no matching catch block is found in the current function, any automatic (local nonstatic) objects in the current function are destroyed and the function exits immediately. A search for a matching catch block continues with the function that called the current function. This process continues up to function main.
If there is no match in any of the catch blocks, the program is normally terminated with a call to the predefined function terminate(). By default, terminate() calls abort(), which destroys all remaining objects and exits from the program. This default behavior can be changed by calling the set_terminate() function.
Exception handling is designed to support only synchronous exceptions, such as array range checks. The term synchronous exception means that exceptions can only be originated from throw expressions.
The C++ standard supports synchronous exception handling with a termination model. Termination means that once an exception is thrown, control never returns to the throw point.
Exception handling is not designed to directly handle asynchronous exceptions such as keyboard interrupts. However, you can make exception handling work in the presence of asynchronous events if you are careful. For instance, to make exception handling work with signals, you can write a signal handler that sets a global variable, and create another routine that polls the value of that variable at regular intervals and throws an exception when the value changes.