异常
try…catch…finally执行顺序
1.看是否有return或者throw new Exception()
return语句和throw 意味着调用结束,因此若是在try块外/catch块/finally块中存在有return语句,那么只会被调用一次。
return的执行优先级为finally > catch > try。
2. 除去return和throw语句外的其他语句,直到发生异常时,执行优先级为try > catch > finally。
public class ExceptionBuilder {
public String buildException() throws Exception {
try{
System.out.println("try");
int result = 10 / 0;
}catch (Exception e){
System.out.println("异常1");
throw new Exception("抛出异常1");
}finally {
System.out.println("异常2");
return "return异常2";
}
}
public static void main(String[] args) throws Exception {
String s = new ExceptionBuilder().buildException();
System.out.println(s);
}
}
执行结果如下: