try-catch-finally执行顺序

先给结论:

1. 不管try中有没有出现异常, finally都会被执行
2. 当try中有return时, 会先执行finally, 再return
3. 当try中出现异常时且catch中有return时, 先执行finally后, 再return

测试代码:

配合断点调试一起食用

 1 /**
 2  * Created by IntelliJ IDEA.
 3  *
 4  * @Auther: ShaoHsiung
 5  * @Date: 2018/9/5 20:54
 6  * @Title:
 7  * @Description:
 8  *      1. 不管try中有没有出现异常, finally都会被执行
 9  *      2. 当try中有return时, 会先执行finally, 再return
10  *      3. 当try中出现异常时且catch中有return时, 先执行finally后, 再return
11  */
12 public class ExceptionTest {
13     public static void main(String[] args) {
14         System.out.println("方法执行前");
15         method();
16         System.out.println("方法执行后");
17     }
18 
19     private static void method() {
20         try {
21             System.out.println("try");
22             int i = 1 / 0;
23             //return;
24         } catch (Exception e) {
25             System.out.println("catch");
26             return;
27         } finally {
28             System.out.println("finally");
29         }
30     }
31 }
原文地址:https://www.cnblogs.com/shaohsiung/p/9594498.html