Java Reference
In-Depth Information
How It Works
The
throw
keyword allows you to explicitly generate an exceptional condition. When
the current thread throws an exception, it doesn't execute anything beyond the
throw
statement and instead transfers control to the
catch
clause (if there are any) or ter-
minates the thread.
Note
When throwing an exception, be sure that you really want to throw it. If an ex-
ception is not caught as it propagates up the stack, it will terminate the thread that is ex-
ecuting (also known as unraveling). If your program has only one main thread, an un-
caught exception will terminate your program.
9-4. Catching Multiple Exceptions
Problem
A block of code in your application has the tendency to throw multiple exceptions. You
want to catch each of the exceptions that may occur within a
try
block.
Solution 1
More than one
catch
clause can be specified in situations where multiple exceptions
occur within the same block. Each
catch
clause can specify a different exception to
handle, so that each exception can be handled in a different manner. In the following
code, two
catch
clauses are used to handle an
IOException
and a
ClassNotFoundException
.
try {
Class<?> stringClass
= Class.forName("java.lang.String");
FileInputStream in = new
FileInputStream("myFile.log") ; // Can throw IOException
in.read();