下面這段代碼的執行結果是怎樣的呢?
publc int test(){int x;try{x = 1;return x;}catch(Exception e){x = 2;return x;}finally{x = 3;}}
相信對Java比較熟悉的朋友馬上會說出正確答案:正常返回1,異常返回2。我第一次看到這段代碼時,對於finally裡面的x=3產生了疑惑,不確定最後返回的x是否變成了3,直到從《深入理解Java虛擬機器》裡面找到了這段代碼的位元組碼,才明白其運行機制。下面是上面這段Java代碼的位元組碼:
public int test(); Code: Stack=1, Locals=5, Args_size=1 0: iconst_1 //將1寫入棧頂 1: istore_1 //將棧頂值(1)寫入第2個int型本地變數 2: iload_1 //將第2個int型本地變數load到棧頂(Return語句的開始) 3: istore 4 //儲存棧頂值到第4個int型本地變數,此時x=1 5: iconst_3 //將3寫入棧頂(Finally開始) 6: istore_1 //將3寫入第2個int型本地變數 7: iload 4 //將第4個int型本地變數的值laod到棧頂 9: ireturn //返回棧頂的值 10: astore_2 11: iconst_2 12: istore_1 13: iload_1 14: istore 4 16: iconst_3 17: istore_1 18: iload 4 20: ireturn 21: astore_3 22: iconst_3 23: istore_1 24: aload_3 25: athrow
從上面的位元組碼可以看出,Return語句被分為兩部分:istore 4和iload 4&ireturn,在store和load之間插入的是finally代碼,x的值首先被存放到一個指定的位置,再執行finally語句,這時finally中的代碼已無法影響傳回值了。