Exception handling provides a way for a function that encounters an unusual situation to throw an exception and pass control to a direct or indirect caller of that function. The caller may or may not be able to handle the exception. Code that intercepts an exception is called a handler. Regardless of whether or not the caller can handle an exception, it may rethrow the exception so it can be intercepted by another handler.
C++ provides three language constructs to implement exception handling:
Within a function, any unusual situation can be flagged with a throw expression. The throw expression is of type void. Your program can throw an object to pass information back to the caller. Any object can be thrown , including the object that caused the exception or an object constructed when the exception occurred.
A throw expression, or a call to a function that may throw an exception, should be enclosed within a try block. If the called function throws an exception and an exception handler is defined to catch the type of the object thrown, the exception handler is executed. In C++, a catch block implements an exception handler. A try block must be accompanied by one or more catch clauses, otherwise the compiler will flag it as an error.
A catch block follows immediately after a try statement or immediately after another catch block. A catch block includes a parenthesized exception declaration containing optional qualifiers, a type, and an optional variable name. The declaration specifies the type of object that the exception handler may catch. Once an exception is caught, the body of the catch block is executed. If no handler catches an exception, the program is terminated.
Exception handling is not strictly synonymous with error handling, because the implementation allows the passing of an exception whether or not an error actually occurred. You can use exception handlers for things other than handling errors. For example, you can transfer control back to the original caller of a function. You might use this if you wanted to process the Quit key in a program and transfer control back to the driver program when the user types Quit. To do this exception handlers could be used to throw an object back to the driver.
C++ exception handling is not the same as OS/2 exception handling. A C++ exception exists only within the C++ language. An OS/2 exception is generated by the operating system, and can be used by the IBM C and C++ Compilers library to generate a signal. In this section, the term exception refers to a C++ exception.
Formal and Informal Exception Handling
Catch Blocks
Try Blocks
Throw Expressions
Using Exception Handling
Transferring Control