Java中Return和Finally執行順序的實現

來源:互聯網
上載者:User

下面這段代碼的執行結果是怎樣的呢?

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中的代碼已無法影響傳回值了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.