There are three keywords for exception handling in C++:
try
catch
throw
A try block is a group of C++ statements, normally enclosed in braces { }, which might cause an exception. This grouping restricts exception handlers to exceptions generated within the try block. Each try block has one or more associated catch blocks.
A catch block is a group of C++ statements that are used to handle a specific thrown exception. One or more catch blocks, or handlers, should be placed after each try block. A catch block is specified by:
The keyword catch
A catch parameter, enclosed in parentheses (), which corresponds to a specific type of exception that may be thrown by the try block
A group of statements, enclosed in braces { }, whose purpose is to handle the exception
The throw statement is used to throw an exception and its value to a subsequent exception handler. A regular throw consists of the keyword throw and an expression. The result type of the expression determines which catch block receives control. Within a catch block, the current exception and value may be re-thrown simply by specifying the throw keyword alone (with no expression).
In the following example, the function call in the try block passes control to f(), which throws an exception of type Overflow. This exception is handled by the catch block, which handles type Overflow exceptions.
class Overflow { // ... public: Overflow(char,double,double); }; void f(double x) { // ... throw Overflow('+',x,3.45e107); } int main() { try { // ... f(1.2); //... } catch(Overflow& oo) { // handle exceptions of type Overflow here } }