The try Block:
The first step in constructing an exception handler is to enclose the code that might throw an exception within a
try
block. In general, a
try
block looks like the following:
try {
code
}
catch and finally blocks . . .
The segment in the example labeled
code
contains one or more legal lines of code that could throw an exception.
To construct an exception handler for the
writeList
method from the
ListOfNumbers
class, enclose the exception-throwing statements of the
writeList
method within a
try
block. There is more than one way to do this. You can put each line of code that might throw an exception within its own
try
block and provide separate exception handlers for each. Or, you can put all the
writeList
code within a single
try
block and associate multiple handlers with it. The following listing uses one
try
block for the entire method because the code in question is very short.
private List<Integer> list;
private static final int SIZE = 10;
PrintWriter out = null;
try {
System.out.println("Entered try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
}
catch and finally statements . . .
If an exception occurs within the
try
block, that exception is handled by an exception handler associated with it. To associate an exception handler with a
try
block, you must put a
catch
block after it;
The catch Blocks:
You associate exception handlers with a
try
block by providing one or more
catch
blocks directly after the
try
block. No code can be between the end of the
try
block and the beginning of the first
catch
block.
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
Each
catch
block is an exception handler and handles the type of exception indicated by its argument. The argument type,
ExceptionType
, declares the type of exception that the handler can handle and must be the name of a class that inherits from the
Throwable
class. The handler can refer to the exception with
name
.
The following are two exception handlers for the
writeList
method — one for two types of checked exceptions that can be thrown within the
try
statement:
try {
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: "
+ e.getMessage());
throw new SampleException(e);
} catch (IOException e) {
System.err.println("Caught IOException: "
+ e.getMessage());
}
Catching More Than One Type of Exception with One Exception Handler:
In Java SE 7 and later, a single
catch
block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
In the
catch
clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (
|
):
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
Note: If a
catch
block handles more than one exception type, then the
catch
parameter is implicitly
final
. In this example, the
catch
parameter
ex
is
final
and therefore you cannot assign any values to it within the
catch
block.
The finally Block:
The finally
block always executes when the try
block exits. This ensures that the finally
block is executed even if an unexpected exception occurs. But finally
is useful for more than just exception handling it allows the programmer to avoid having cleanup code accidentally bypassed by a return
, continue
, or break
. Putting cleanup code in a finally
block is always a good practice, even when no exceptions are anticipated.
Note:
If the JVM exits while the
try
or
catch
code is being executed, then the
finally
block may not execute. Likewise, if the thread executing the
try
or
catch
code is interrupted or killed, the
finally
block may not execute even though the application as a whole continues.
Important:
The
finally
block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a
finally
block to ensure that resource is
always recovered.
If you are using Java SE 7 or later, consider using the
try-
with-resources statement in these situations, which automatically releases system resources when no longer needed