If an exception occurs as the result of a statement in a try
block, the try
block expires (i.e., terminates immediately). Next, the program searches for the first catch
handler that can process the type of exception that occurred. The program locates the matching catch
by comparing the thrown exception’s type to each catch
’s exception-parameter type until the program finds a match. A match occurs if the types are identical or if the thrown exception’s type is a derived class of the exception-parameter type. When a match occurs, the code in the matching catch
handler executes. When a catch
handler finishes processing by reaching its closing right brace (}
), the exception is considered handled and the local variables defined within the catch
handler (including the catch
parameter) go out of scope. Program control does not return to the point at which the exception occurred (known as the throw point), because the try
block has expired. Rather, control resumes with the first statement (line 43) after the last catch
handler following the try
block. This is known as the termination model of exception handling. Some languages use the resumption model of exception handling, in which, after an exception is handled, control resumes just after the throw point. As with any other block of code, when a try block terminates, local variables defined in the block go out of scope.
Common Programming Error 17.4
Logic errors can occur if you assume that after an exception is handled, control will return to the first statement after the throw point.
Error-Prevention Tip 17.2
With exception handling, a program can continue executing (rather than terminating) after dealing with a problem. This helps ensure the kind of robust applications that contribute to what’s called mission-critical computing or business-critical computing.
If the try
block completes its execution successfully (i.e., no exceptions occur in the try
block), then the program ignores the catch
handlers and program control continues with the first statement after the last catch
following that try
block.
If an exception that occurs in a try
block has no matching catch
handler, or if an exception occurs in a statement that is not in a try
block, the function that contains the statement terminates immediately, and the program attempts to locate an enclosing try
block in the calling function. This process is called stack unwinding and is discussed in Section 17.4.
3.16.81.33