ClassNotFoundException | Exception is
not a union of alternatives and is not
allowed in a multi-catch statement.
Similarly, ClassNotFoundException |
ClassNotFoundException is also disallowed, because a type is also a subtype
of itself.
A multi-catch statement is semantically equivalent to as many catch clauses
as types take part in a union type where
the exception reference is implicitly
final. Our previous example is semantically equivalent to the code shown in
Listing 14.
Compilers are not required to perform
this code expansion. Given that each
block is required to perform operations
that are supported by the union of all
alternative exception types, a single
effective catch block is compiled per
multi-catch statement.
This is easy to check by decompiling
the code for our example, as shown
in Listing 15, because we see that the
exception table has jumps to the
same address.
We mentioned earlier that exceptions
of a union of alternatives are implicitly
considered to be final. There is more to
it, though, because any exception that
is not used as a left-hand operand to
an assignment is now considered to be
effectively final. This means that the
exception e in the following code is now
considered to be final, although it has
not been declared so:
By contrast, it is not considered to be
effectively final in the following con-
trived example:
catch (ClassNotFoundException e) {
e.printStackTrace();
e = new ClassNotFoundException();
throw e;
}
try {
Class<?> stringClass = Class.forName(" java.lang.String");
Object instance = stringClass.newInstance();
Method toStringMethod = stringClass.getMethod("toString");
System.out.println( toStringMethod.invoke(instance));
} catch (final ClassNotFoundException e) {
e.printStackTrace();
} catch (final InstantiationException e) {
e.printStackTrace();
} catch (final IllegalAccessException e) {
e.printStackTrace();
} catch (final NoSuchMethodException e) {
e.printStackTrace();
} catch (final Invocation TargetException e) {
e.printStackTrace();
}
JAVA IN ACTION
ABOUT US
Download all listings in this issue as text
blog
catch (ClassNotFoundException e) {
e.printStack Trace();
}
It is perfectly legal to declare as final
an exception reference in a multi-catch
clause. It is, however, discouraged as a
matter of style given that this is implic-
itly the case.
throw expression of some exception type
E actually throws an exception of type
E, a subtype of E, or any type that can
be thrown by a corresponding try block
in a catch block. Then, each catch clause
must be a type, subtype, or supertype of