测试用例
public class TestExceptions {
public static void main(String[] args){
try {
String result = "";
try {
int i= 0;
double val = 10/i;
System.out.println("try ok!");
result = "ok!";
} catch (Exception e){
result = "fail";
e.printStackTrace();
throw new Exception(e.getMessage());
} finally {
System.out.println("here in finally, result=="+ result);
}
} catch (Exception e){
System.out.println("outter try catch, exception=="+ e.getMessage());
}
}
}
输出结果:
java.lang.ArithmeticException: / by zero
at TestExceptions.main(TestExceptions.java:12)
here in finally, result==fail
outter try catch, exception==/ by zero
结论:
try块代码抛出异常,则转到相应的catch块,被捕获异常;
在catch执行完,转入外部代码之前,先执行finally块。
无论是否抛出异常,finally块的代码都会被执行到。
本文深入探讨了Java中try-catch-finally机制的运作原理,通过具体示例展示了如何捕获并处理异常。重点阐述了try块、catch块和finally块的功能及执行流程,为开发者提供了一套全面的异常处理解决方案。

被折叠的 条评论
为什么被折叠?



