try、catch、finally
- 出现异常+finally有return
public static int test(){
try {
int n = 1/0;
return 1;
} catch (Exception e) {
e.printStackTrace();
return 2;
} finally {
return 3;
}
}
使用finally的return
- 出现异常,finally没有return
public static int test(){
try {
int n = 1/0;
return 1;
} catch (Exception e) {
e.printStackTrace();
return 2;
} finally {
}
}
使用catch中的return
- 没有异常,finally有return
public static int test(){
try {
int n = 2/2;
return n;
} catch (Exception e) {
e.printStackTrace();
return 2;
} finally {
return 3;
}
}
使用finally中的return
- 没有异常,finally没有return
public static int test(){
try {
int n = 2/2;
return n;
} catch (Exception e) {
e.printStackTrace();
return 2;
} finally {
}
}
使用try中的return
结论:finally 代码块中的代码用于处理善后工作, 会在最后执行,也一定会被执行。当遇到try或catch中return或throw之类可以终止当前方法的代码时,jvm会先去执行finally中的语句,当finally中的语句执行完毕后才会返回来执行try/catch中的return,throw语句。如果finally中有return或throw,那么将执行这些语句,不会再执行try/catch中的return或throw语句。