Java Reference
In-Depth Information
interface Type1 {
void f() throws CloneNotSupportedException;
}
interface Type2 {
void f() throws InterruptedException;
}
interface Type3 extends Type1, Type2 {
}
public class Arcane3 implements Type3 {
public void f() {
System.out.println("Hello world");
}
public static void main(String[] args) {
Type3 t3 = new Arcane3();
t3.f();
}
}
Solution 37: Exceptionally Arcane
The first program,
Arcane1
, illustrates a basic principle of checked exceptions. It may look as
though it should compile: The
try
clause does I/O, and the
catch
clause catches
IOException
. But
the program does not compile because the
println
method isn't declared to throw any checked
exceptions, and
IOException
is a checked exception. The language specification says that
it is a
compile-time error for a
catch
clause to catch a checked exception type
E
if the corresponding
TRy
clause can't throw an exception of some subtype of
E
[JLS 11.2.3].
By the same token, the second program,
Arcane2
, may look as though it shouldn't compile, but it
does. It compiles because its sole
catch
clause checks for
Exception
. Although the JLS is not
terribly clear on this point,
catch clauses that catch
Exception
or
Throwable
are legal regardless
of the contents of the corresponding
try
clause
. Although
Arcane2
is a legal program, the
contents of its
catch
clause will never be executed; the program prints nothing.
Search WWH ::
Custom Search