Java Reference
In-Depth Information
12.5.4
Multi-catch Java 7
A new feature was introduced in Java 7 that allows multiple exceptions to be handled in the
same catch block. This reduces the code duplication involved when the same recovery action is
required for different exception types. The different exception types are written in front of the
exception variable name, separated by the “ | ” symbol. See Code 12.13.
Code 12.13
Multi-catch in Java 7
try {
...
ref.process();
...
}
catch (EOFException | FileNotFoundException e) {
// Take action appropriate to both exceptions.
...
}
Java 7 also introduced another new feature to the try statement, called “try-with-resources” or
“automatic resource management” (ARM). We shall cover this briefly, along with file handling,
in Section 12.9.
Exercise 12.31 Enhance the try statements you wrote as solutions to Exercises 12.28 and
12.29 so that they handle checked and unchecked exceptions in different catch blocks.
Exercise 12.32 What is wrong with the following try statement?
Person p = null;
try {
p = database.lookup(details);
System.out.println("The details belong to: " + p);
}
catch(Exception e) {
// Handle any checked exceptions ...
...
}
catch(RuntimeException e) {
// Handle any unchecked exceptions ...
...
}
12.5.5
Propagating an exception
So far, we have suggested that an exception must be caught and handled at the earliest possible
opportunity. That is, an exception thrown in a method process would have to be caught and
handled in the method that called process . In fact, this is not strictly the case, as Java allows
 
Search WWH ::




Custom Search