public class D {
void myMethod() {
try {
throw new IllegalArgumentException();
} catch (NullPointerException npex) {
System.out.println("NullPointerException thrown ");
} catch (Exception ex) {
System.out.println("Exception thrown ");
} finally {
System.out.println("Done with exceptions ");
}
System.out.println("myMethod is done");
}
public static void main(String args[]) {
D d = new D();
d.myMethod();
}
Run Code Online (Sandbox Code Playgroud)
}
我不明白怎么"myMethod is done"也被打印出来.抛出了异常,因此它假设找到一个匹配的catch并执行finally块,但它继续在该myMethod方法上打印myMethod is done,而不是finally块的一部分.为什么?
这就是try-catch-finally的工作方式.因为您捕获了异常,所以它被认为已被处理,并且执行继续正常进行.
如果你没有抓住它,或者重新抛出它,那么"myMethod就完成了"就不会被打印出来,并且异常会在堆栈中冒出来,直到它被别人抓到.
请注意,finally块始终执行,异常或否.
另一方面,如果您有以下内容:
void myMethod() {
try {
throw new IllegalArgumentException();
System.out.println("Line after exception"); /// new line added here
} catch (NullPointerException npex) {
System.out.println("NullPointerException thrown ");
} catch (Exception ex) {
System.out.println("Exception thrown ");
} finally {
System.out.println("Done with exceptions ");
}
System.out.println("myMethod is done");
}
public static void main(String args[]) {
D d = new D();
d.myMethod();
}
Run Code Online (Sandbox Code Playgroud)
然后"异常后线"将不打印.
| 归档时间: |
|
| 查看次数: |
318 次 |
| 最近记录: |