關於異常跳轉的底層瞭解

今天遇到了一個問題

public int inc() {

   int x;

   try {

       x = 1;

       return x;

   } catch (Exception e) {

       x = 2;

       return x;

   } finally {

       x = 3;

   }

}

判斷返回值。後來看Java虛擬機的時候才知道底層的知識。先看編譯好的class文件

public int inc();

    0  iconst_1

    1  istore_1 [x]

    2  iload_1 [x]

    3  istore 4

    5  iconst_3

    6  istore_1 [x]

    7  iload 4

    9  ireturn

   10  astore_2 [e]

   11  iconst_2

   12  istore_1 [x]

   13  iload_1 [x]

   14  istore 4

   16  iconst_3

   17  istore_1 [x]

   18  iload 4

   20  ireturn

   21  astore_3

   22  iconst_3

   23  istore_1 [x]

   24  aload_3

   25  athrow

   省略其他的不必要信息,0-3行完成了對對變量X的賦值,同時將X值賦值到第四個本地變量表中。

   5-9行將X賦值爲3, iload 4 將本地變量 讀入到方法棧頂, ireturn 返回棧頂變量值。

   如果出現異常則跳轉到10行繼續。此時將X賦值爲2,同時複製到本地變量表4,返回時iload 4 將本        地變量 讀入到方法棧頂, ireturn 返回棧頂變量值。

    如果出現異常且不爲Exception則跳轉到21行執行。


   查看Exception  table

        Exception Table:

       [pc: 0, pc: 5] -> 10 when : java.lang.Exception

       [pc: 0, pc: 5] -> 21 when : any

       [pc: 10, pc: 16] -> 21 when : any

   
   可以看到跳轉的行數和條件。

   此時可以得到結論:

   沒有異常返回1,有Exception異常返回2,非Exception無返回值正常退出。

   感謝深入《深入理解JVM虛擬機》這本書的啓示。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章