A function might use a resource—like a file—and might want to release the resource (i.e., close the file) if an exception occurs. An exception handler, upon receiving an exception, can release the resource then notify its caller that an exception occurred by rethrowing the exception via the statement
throw;
Regardless of whether a handler can process an exception, the handler can rethrow the exception for further processing outside the handler. The next enclosing try
block detects the rethrown exception, which a catch
handler listed after that enclosing try
block attempts to handle.
Executing an empty throw
statement outside a catch
handler terminates the program immediately.
Figure 17.3 demonstrates rethrowing an exception. In main
’s try
block (lines 25–29), line 27 calls function throwException
(lines 8–21). The throwException
function also contains a try
block (lines 10–13), from which the throw
statement in line 12 throw
s a Standard Library exception
object. Function throwException
’s catch
handler (lines 14–18) catches this exception, prints an error message (lines 15–16) and rethrows the exception (line 17). This terminates the function and returns control to line 27 in the try
block in main
. The try
block terminates (so line 28 does not execute), and the catch
handler in main
(lines 30–32) catches this exception and prints an error message (line 31). Since we do not use the exception parameters in this example’s catch
handlers, we omit the exception parameter names and specify only the type of exception to catch (lines 14 and 30).