Java Reference
In-Depth Information
In this example, an exception that can be handled by the inner
try
—in this case, a divide-
by-zero error—allows the program to continue. However, an array boundary error is caught
by the outer
try
, which causes the program to terminate.
Although certainly not the only reason for nested
try
statements, the preceding program
makes an important point that can be generalized. Often nested
try
blocks are used to allow
different categories of errors to be handled in different ways. Some types of errors are cata-
strophic and cannot be fixed. Some are minor and can be handled immediately. You might
use an outer
try
block to catch the most severe errors, allowing inner
try
blocks to handle
less serious ones.
Throwing an Exception
The preceding examples have been catching exceptions generated automatically by the
JVM. However, it is possible to manually throw an exception by using the
throw
statement.
Its general form is shown here:
throw
exceptOb
;
Here,
exceptOb
must be an object of an exception class derived from
Throwable
.
Here is an example that illustrates the
throw
statement by manually throwing an
Arith-
meticException
:
The output from the program is shown here: