Main Page

Previous Page
Next Page

[Page 834 (continued)]

16.14. Other Error-Handling Techniques

We have discussed several ways to deal with exceptional situations prior to this chapter. The following summarizes these and other error-handling techniques:

  • Ignore the exception. If an exception occurs, the program might fail as a result of the uncaught exception. This is devastating for commercial software products or for special-purpose software designed for mission-critical situations, but, for software developed for your own purposes, ignoring many kinds of errors is common.

    Common Programming Error 16.10

    Aborting a program component due to an uncaught exception could leave a resourcesuch as a file stream or an I/O devicein a state in which other programs are unable to acquire the resource. This is known as a "resource leak."

  • Abort the program. This, of course, prevents a program from running to completion and producing incorrect results. For many types of errors, this is appropriate, especially for nonfatal errors that enable a program to run to completion (potentially misleading the programmer to think that the program functioned correctly). This strategy is inappropriate for mission-critical applications. Resource issues also are important here. If a program obtains a resource, the program should release that resource before program termination.

  • Set error indicators. The problem with this approach is that programs might not check these error indicators at all points at which the errors could be troublesome.

  • Test for the error condition, issue an error message and call exit (in <cstdlib>) to pass an appropriate error code to the program's environment.

  • Use functions setjump and longjump. These <csetjmp> library functions enable the programmer to specify an immediate jump from a deeply nested function call to an error handler. Without using setjump or longjump, a program must execute several returns to exit the deeply nested function calls. Functions setjump and longjump are dangerous, because they unwind the stack without calling destructors for automatic objects. This can lead to serious problems.

  • Certain specific kinds of errors have dedicated capabilities for handling them. For example, when operator new fails to allocate memory, it can cause a new_handler function to execute to handle the error. This function can be customized by supplying a function name as the argument to set_new_handler, as we discuss in Section 16.11.

Previous Page
Next Page