1.如果没有异常,先执行try代码块,再执行finally代码块;
try{
System.out.println(111);
}catch(Exception e){
System.out.println(222);
}finally{
System.out.println(333);
}
结果:111 333
2.如果有异常,先执行try代码块,再执行catch代码块,最后执行finally代码块;
int i = 1;
try{
System.out.println(111);
int a = i/0;
}catch(Exception e){
System.out.println(222);
}finally{
System.out.println(333);
}
结果:111 222 333
3.如果在try代码块加入return,finally代码块在return前执行;
try{
System.out.println(111);
return;
}catch(Exception e){
System.out.println(222);
}finally{
System.out.println(333);
}
结果:111 333
4.如果在try代码块加入return且有异常,
public class Test15 {
public static int test3(){
try{
int a = 5/0;
return 1;
}catch (ArithmeticException e){
System.out.println(222);
return 2;
}finally {
System.out.println(333);
}
}
public static void main(String[] args) throws MyException {
System.out.println(test3());
}
结果:222 333 2
5.try代码块中有return
public static String test1(){
try{
System.out.println(111);
return test2();
}finally{
System.out.println(333);
}
}
public static String test2() {
System.out.println(444);
return "test2 return";
}
public static void main(String[] args) throws MyException {
System.out.println(test1());
}
结果:111 444 333 test2 return
return test2() 等价于
String tmp = test2();
return tmp;
总结:如有异常,按try catch finally 的顺序运行
try 和catch代码块中有return ,则finally代码块在return之前运行,
如果finally代码块中有return,则提前结束进程。