Java Reference
In-Depth Information
Beginning with JDK 7, Java's exception handling mechanism has been expanded with the
addition of three features. The first supports automatic resource management , which auto-
mates the process of releasing a resource, such as a file, when it is no longer needed. It
is based on an expanded form of try , called the try -with-resources statement, and it is de-
scribed in Chapter 10 , when files are discussed. The second new feature is called multi-
catch , and the third is sometimes called final rethrow or more precise rethrow . These two
features are described here.
Multi-catch allows two or more exceptions to be caught by the same catch clause. As
you learned earlier, it is possible (indeed, common) for a try to be followed by two or more
catch clauses. Although each catch clause often supplies its own unique code sequence, it
is not uncommon to have situations in which two or more catch clauses execute the same
code sequence even though they catch different exceptions. Instead of having to catch each
exception type individually, you can now use a single catch clause to handle the exceptions
without code duplication.
To create a multi-catch, specify a list of exceptions within a single catch clause. You do
this by separating each exception type in the list with the OR operator. Each multi-catch
parameter is implicitly final . (You can explicitly specify final , if desired, but it is not ne-
cessary.) Because each multi-catch parameter is implicitly final , it can't be assigned a new
value.
Here is how you can use the multi-catch feature to catch both ArithmeticException and
ArrayIndexOutOfBoundsException with a single catch clause:
Here is a simple program that demonstrates the use of this multi-catch:
Search WWH ::




Custom Search