1.即使违例不在当前的catch从句里捕获,finally都会在违例控制机制转到更高级别搜索一个控制器之前得以执行。
如下:
package com.cqdxwjd.chapter9;
class Ex extends Exception {
}
public class AlwaysFinally {
public static void main(String[] args) {
System.out.println("Entering first try block");
try {
System.out.println("Entering second try block");
try {
throw new Ex();
} finally {
System.out.println("finally in 2nd try block");
}
} catch (Ex e) {
System.out.println("Caught Ex in first try block");
} finally {
System.out.println("finally in 1st try block");
}
}
}
输出:
Entering first try block
Entering second try block
finally in 2nd try block
Caught Ex in first try block
finally in 1st try block
2.有finally从句时,违例可能会丢失,代码如下:
package com.cqdxwjd.chapter9;
class VeryImportantException extends Exception {
public String toString() {
return "A very important exception!";
}
}
class HoHumException extends Exception {
public String toString() {
return "A trivial exception";
}
}
public class LostMessage {
void f() throws VeryImportantException {
throw new VeryImportantException();
}
void dispose() throws HoHumException {
throw new HoHumException();
}
public static void main(String[] args) throws Exception {
LostMessage lm = new LostMessage();
try {
// lm.f();
lm.dispose();
} finally {
lm.f();
lm.dispose();
}
}
}
输出:
Exception in thread “main” A trivial exception
at com.cqdxwjd.chapter9.LostMessage.dispose(LostMessage.java:21)
at com.cqdxwjd.chapter9.LostMessage.main(LostMessage.java:29)
可以看到,这里不存在VeryImportantException(非常重要的违例)的迹象,它只是简单地被finally 从句中的HoHumException 代替了。