C++ Programming Guide

Using Exception Handling Keywords

There are three keywords for exception handling in C++:

try

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.

catch

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:

throw

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
	}
}