众所周知,try{}catch(){}finally{}是异常处理的一个标准写法,那finally一定会执行吗?请看下边实例。
一、会执行的情况
public String get(){
int a = 0;
int b = 3;
try {
int c = b/a; //会发生分母不能为0 的异常
return "结果";
}catch (Exception e){
System.out.println("this have a exception"+e.getMessage());
return null;
}
finally {
System.out.println("finally over");
return "100";
}
}
上述代码一定会发生异常,那么在catch里return了会返回 100 还是null?请看下面测试代码和执行结果。
public static void main(String[] args) {
Test test = new Test();
String s = test.get();
System.out.println(s);
}
二、不会执行的情况
1、如果程序在达到try块之前因异常而终止。
2、如果在try或catch块中调用了System.exit(0),这将立即终止JVM,导致finally块不会被执行。
3、如果在try块中调用了Runtime.getRuntime().halt(0),这会直接终止JVM,同样导致finally块不被执行。
4、如果程序因掉电或其他原因突然终止,finally块也不会被执行。
5、如果在执行try块之前有return语句执行,finally块同样不会执行
public String get(){
int a = 0;
int b = 3;
int x = b/a; //try 之前异常
try {
int c = b/a; //会发生分母不能为0 的异常
return "结果";
}catch (Exception e){
System.out.println("this have a exception"+e.getMessage());
return null;
}
finally {
System.out.println("finally over");
return "100";
}
}