| Getting Started | Documentation | Glish | Learn More | Programming | Contact Us |
| Version 1.9 Build 803 |
|
The C++ exceptions are based on the idea of try and catch blocks. The try block contains the code which may throw an exception, and the catch block, which must follow immediately after the try block, contains the handlers for the various exceptions which may be thrown in the try block. So in the simple case, one might have:
try {
if (how_many == 1) throw(MajorError(1));
if (how_many == 2) throw(MinorError(2));
if (how_many == 3) throw(TypedError(3));
} catch (TypedError xx) {
cout << "Caught TypedError" << endl;
} catch (MinorError xx) {
cout << "Caught MinorError" << endl;
} catch (MajorError xx) {
cout << "Caught MajorError" << endl;
}
In this example, depending on the variable
how_many a different exception will be thrown, via throw().
The exception will then be caught by the first catch block that
matches the exception. Thus, if MinorError was derived from
TypedError, then the TypedError block would be executed before
the MinorError block for a thrown MinorError.
It is also possible to have incremental recovery. A caught exception can be rethrown with throw. The following example illustrates this usage:
try {
if (how_many == 1) throw(MajorError(1));
if (how_many == 2) throw(MinorError(2));
if (how_many == 3) throw(TypedError(3));
} catch (MinorError xx) {
cout << "Caught MinorError" << endl;
} catch (MajorError xx) {
cout << "Caught MajorError" << endl;
throw;
} catch (TypedError xx) {
cout << "Caught TypedError" << endl;
}
In this example, the MajorError catch block handles a MajorError
when it occurs and then rethrows the exception so that it could be
handled by other catch blocks. Thus, if MajorError is derived from
TypedError, then the TypedError catch block would have the
opportunity to handle its portion of the error after the MajorError
catch block was finished.
These try/catch blocks can be nested to the level necessary as long as the introductory try is balanced with a closing brace. The following example contains a nested try block:
try {
if (how_many == 0) throw(ExcpError(1));
try {
if (how_many == 1) throw(ExcpError(1));
if (how_many == 2) throw(ExcpError(2));
if (how_many == 3) throw(ExcpError(3));
} catch (ExcpError xx) {
throw(ExcpError(9));
}
} catch (ExcpError xx) {
cout << "Caught ExcpError" << endl;
}