Java Reference
In-Depth Information
Analysis of Rethrown Exceptions
Java 7 improved the mechanism of rethrowing exceptions. Consider the following snippet of code for a method
declaration:
public void test() throws Exception {
try {
// May throw Exception1, or Exception2
}
catch (Exception e) {
// Rethrow the caught exception
throw e;
}
}
The try block may throw Exception1 or Exception2 . The catch block specifies Exception as its parameter
and it rethrows the exception it catches. Prior to Java 7, the compiler sees the catch block throwing an exception of
Exception type and it insisted that, in the throws clause, the test() method must specify that it threw an exception of
the Exception type or the supertype of the Exception type.
Because the try block can throw exceptions of only Exception1 and Exception2 types, the catch block will
rethrow an exception that is always of these two types. Java 7 performs this analysis when an exception is rethrown.
It lets you specify the throws clause of the test() method accordingly. In Java 7, you can specify more specific
exception types, Exception1 and Exception2 , in the test() method's throws clause, as follows:
public void test() throws Exception1, Exception2 {
try {
// May throw Exception1, Exception2 or Exception3
}
catch (Exception e) {
// Rethrow the caught exception
throw e;
}
}
Throwing too Many Exceptions
There is no limit on the number of exception types that a method/constructor can list in its throws clause. However,
it is better to keep the number low. The client that uses a method has to deal with all the exceptions that the method
may throw in one way or another. It is also important to keep in mind that a method should not throw a new type of
exception once it has been designed, implemented, and released to public. If a method starts throwing a new type
of exception after its public release, all client code that call this method must change. It indicates poor design if a
method throws too many exceptions or a new exception is added after its public release. You can avoid these issues
with your method by catching all lower-level exceptions inside your method and rethrowing a higher-level exception.
The exception that you throw may contain the lower-level exception as its cause. Consider the following snippet of
code for a method m1() that throws three exceptions ( Exception1 , Exception2 , and Exception3 ):
public void m1() throws Exception1, Exception2, Exception3 {
// Code for m1() method goes here
}
 
Search WWH ::




Custom Search