finally
1.finally是try-catch块中使用的关键字,无论try-catch是否有异常抛出都会执行finally块中的代码
2.不是代码中所有的finally都会执行,只有在执行到try-catch块时,这个try-catch块中的finally才会执行
1.Try catch 中有return finally还会执行吗
1、不管有没有catch到异常,finally块中代码都会执行;
2、当try和catch中有return时,finally仍然会执行;
2.try-catch-finally的执行顺序
public static void main(String[] args) {
int res = tryTest();
System.out.println(res);
}
private static int tryTest(){
int res = 1;
try{
res = 1/0;
System.out.println("There is try");
return 8;
}catch (Exception e){
System.out.println("There is catch");
//return 6;
}finally {
System.out.println("There is finally");
//return 9;
}
return 10;
}
Result 1:在try块中包含return
There is catch
There is finally
10
Result 2:在finall块中return,取消注释 return 9;注释return 10;
There is catch
There is finally
9
Result 3:在try、catch、finally中都有return
There is catch
There is finally
9
Result 4:不设置异常,res = 1/1,只注释return 10;
There is try
There is finally
9
Result 5:不设置异常,res = 1/1,注释return 10和9;
This is try
There is finally
8
结论:执行顺序 try->finally (->try)或catch->finally(->catch),如果finally中有return则不会执行try和catch中的return。
当try、catch中有return时,也会执行finally。
3.finally不执行的情况
1.不执行try catch,当然也就不会执行finally
2.在执行前出现其他异常,程序中断
3.在执行try或者catch中,有exit退出
try{
res=1/1;
System.out.println("This is try");
System.exit(0);
return 8;
}catch(Exception e){
System.out.println("This is catch");
}finally{
System.out.println("There is finally");
}
Result
This is try