8 Exception Handling
8 Exception Handling
23.1 Introduction
Errors can be dealt with at place error occurs
Easy to see if proper error checking implemented
Harder to read application itself and see how code works
Exception handling
Makes clear, robust, fault-tolerant programs
C++ removes error handling code from "main line" of program
Common failures
new not allocating memory
Out of bounds array subscript
Division by zero
Invalid function parameters
23.1 Introduction (II)
Typically used when error dealt with in different place than where it
occurred
Useful when program cannot recover but must shut down cleanly
Exception handling should not be used for program
control
Not optimized, can harm program performance
23.1 Introduction (III)
Exception handling improves fault-tolerance
Easier to write error-processing code
Specify what type of exceptions are to be caught
Use assert
If assertion false, the program terminates
Ignore exceptions
Use this "technique" on casual, personal programs - not commercial!
Specific errors
Some have dedicated capabilities for handling them
If new fails to allocate memory new_handler function executes to deal with
problem
23.4 Basics of C++ Exception Handling: try,
throw, catch
Format
Enclose code that may have an error in try block
Follow with one or more catch blocks
Each catch block has an exception handler
If exception occurs and matches parameter in catch block,
code in catch block executed
If no exception thrown, exception handlers skipped and
control resumes after catch blocks
throw point - place where exception occurred
Control cannot return to throw point
23.5 A Simple Exception-Handling Example: Divide
by Zero
Unreleased resources
Resources may have been allocated when exception thrown
catch handler should delete space allocated by new and
close any opened files
Rethrowing exceptions
Used when an exception handler cannot process an
exception
Rethrow exception with the statement:
throw;
No arguments
If no exception thrown in first place, calls terminate