Puzzle 37: Exceptionally Arcane
本文主要说明了在使用 Java 异常时,几个比较特殊的地方,注意示例代码中的文字说明。
1. throw 块中的代码必须包含 catch 块中的异常种类,否则不能编译,如:
public class Arcane1 {
public static void main(String[] args) {
/*
* 这里会出现编译错误,因为 try 块中的语句不可能触发 IOException
*/
try {
System.out.println("Hello world");
} catch(IOException e) {
System.out.println("I've never seen println fail!");
}
}
}
2. 对上面的说法,有一个例外,它是 Exception
public class Arcane2 {
public static void main(String[] args) {
/*
* 这里不会报错,和 Arcane1 的说法矛盾了。
*/
try {
// If you have nothing nice to say, say nothing
} catch (Exception e) {
System.out.println("This can't happen");
}
}
}
3. 如果一个类实现了几个接口,而这几个接口中有相同名称的方法,并且都抛出了异常,那么这个类的这种方法抛出的异常是这个方法在不同接口中所抛出异常的交集,如:
interface Type1 {
void f() throws CloneNotSupportedException;
}
interface Type2 {
void f() throws InterruptedException;
}
interface Type3 extends Type1, Type2 {
}
public class Arcane3 implements Type3 {
/*
* 这个方法的异常来自 Type1 和 Type2 两个接口,
* 取 CloneNotSupportedException 和 InterruptedException
* 的交集,此交集为空。
*/
public void f() {
System.out.println("Hello world");
}
public static void main(String[] args) {
Type3 t3 = new Arcane3();
t3.f();
}
}