Java Reference
In-Depth Information
Java 7 added support for catching multiple exceptions using a multi-catch block. You can specify multiple
exceptions types in a multi-catch block. Multiple exceptions are separated by a vertical bar ( | ). In Java 7, the above
code can be written as follows:
try {
// May throw Exception1, Exception2, or Exception3
}
catch (Exception1 | Exception2 | Exception3 e) {
// Handle Exception1, Exception2, and Exception3
}
In a multi-catch block, it is not allowed to have alternative exceptions that are related by subclassing. For
example, the following multi-catch block is not allowed, because Exception1 and Exception2 are subclasses of
Throwable :
try {
// May throw Exception1, Exception2, or Exception3
}
catch (Exception1 | Exception2 | Throwable e) {
// Handle Exceptions here
}
The above snippet of code will generate the following compiler error:
error: Alternatives in a multi-catch statement
cannot be related by subclassing
catch (Exception1 | Exception2 | Throwable e) {
^
Alternative Exception1 is a subclass of alternative Throwable
1 error
Summary
An exception is the occurrence of an abnormal condition in a Java program where a normal path of execution is not
defined. Java lets you separate the code that performs the actions from the code that handles exceptions that may
occur when the actions are performed.
Use a try-catch block to place your action-performing code in the try block and exception-handling code in the
catch block. A try block may also have a finally block, which is typically used to clean up resources used in the try
block. You can have a combination of try-catch , try-catch-finally , or try-finally blocks. Java 7 added supported
for a try-with-resources block that comes in handy to close resources automatically.
There are two types of exceptions: checked exceptions and unchecked exceptions. The compiler makes sure that
all checked exceptions are handled in the program or the program declares them in a throws clause. Handling or
declaring unchecked exceptions is optional.
 
Search WWH ::




Custom Search