您的位置:首页 > 编程语言 > Java开发

Java try-catch-finally 代码执行顺序

2015-07-03 15:02 603 查看

测试用例

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块的代码都会被执行到。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: