Catching Exceptions

You can declare a handler to catch many types of exceptions. The allowable objects that a function can catch are declared in the parentheses following the catch keyword (the catch argument). You can catch objects of the fundamental types, base and derived class objects, references, and pointers to all of these types. You can also catch const and volatile types.

You can also use the catch(...) form of the handler to catch all thrown exceptions that have not been caught by a previous catch block. The ellipsis in the catch argument indicates that any exception thrown can be handled by this handler.

If an exception is caught by a catch(...) block, there is no direct way to access the object thrown. Information about an exception caught by catch(...) is very limited. You can declare an optional variable name if you want to access the thrown object in the catch block.

A catch block can only catch accessible objects. The object caught must have an accessible copy constructor.

An argument in the catch argument of a handler matches an argument in the expression of the throw expression (throw argument) if any of the following conditions is met:


Note: If the type of the thrown object is const or volatile , the catch argument must also be a const or volatile for a match to occur. However, a const, volatile, or reference type catch argument can match a nonconstant, nonvolatile , or nonreference object type. A nonreference catch argument type matches a reference to an object of the same type.

Always place a catch block that catches a derived class before a catch block that catches the base class of that derived class (following a try block). If a catch block for objects of a base class is followed by a catch block for objects of a derived class of that base class, the latter block is flagged as an error.

A catch block of the form catch(...) must be the last catch block following a try block or an error occurs. This placement ensures that the catch(...) block does not prevent more specific catch blocks from catching exceptions intended for them.



C++ Exception Handling Overview
Reference


Copy Constructor
Copy by Initialization
Member Access
Using Exception Handling
Transferring Control
Exception Specifications
Nested Try Blocks
Rethrowing an Exception