java中finally什么时候执行?return语句与其执行相关顺序是怎样的?
package cn.gestwr.test;
/***
*@author gestwr
*@data 2022/8/12
*/
public class TestFinally {
public static void main(String[] args) {
System.out.println("Hello World!");
System.out.println("This is " + testFinally());
}
static int testFinally() {
int a = 0;
try {
System.out.println("This is try");
return a;
//return a / 0;
} catch (Exception e) {
e.printStackTrace();
System.out.println("This is catch");
//throw e;
//a = 1;
//return a; //如果没有throw 或者 finall块里没有return,则返回该处的值
} finally {
System.out.println("This is finally");
//a = 2;
//return a; //掩盖所有return的值
}
//前面如果有throw-》finally执行完后,后面的语句不会执行
a = 3; //如果try块一切正常,finally没有return,最终返回值是try块的0 而不是这里的3
return a;
}
}
注:
try块或者catch块中有 System.exit(0);
语句,则程序到此直接退出,不执行finally块