When to recover an exception

There are several reasons for recovering an exception:

Try to recover from an exception only when you can take a sensible action. Limit your handlers to fairly narrow categories of errors, with an obvious recovery action. If you do not know what really happened, it is better to let the error surface than to try a random recovery action and hope that the problem goes away. If the recovery action does not work, you might make it worse.

Do not catch TStandardException or (...) and fail to rethrow it. An exception to this rule is in the Application framework, which catches unhandled exceptions, puts up an alert for the end user, and then attempts to continue. Another exception is within the body of destructors. If a destructor does something that can generate an exception, surround that action with a try-catch block that fields any exception (using catch(...)) and then attempts to continue. As discussed in the previous section, do not allow an exception to escape from a destructor.

Separate error recovery and resource cleanup handlers occurring in the same function. It is better to avoid resource cleanup inside the error recovery handler because doing so might result in your duplicating cleanup code throughout your handlers. You can nest the recovery handlers inside the try block for the resource cleanup handlers. Or even better, use the technique described in "Automatic objects" on page 104 to avoid resource cleanup handlers altogether. But don't do both in the same handler.

Use assertions to signal error conditions due to programming error, which clients wouldn't want to recover from. A violated assertion drops into a debugger during testing, but throws a standard programming error exception in production use. If the error can occur other than from programmer error, or if clients might want to catch and recover from it, use an exception you define yourself.

[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker