java中 異常中的finally處理效果

來源:互聯網
上載者:User

標籤:catch   print   static   cat   調用   --   gen   interrupt   sys   

 

main方法中

try {
System.out.println(aa());
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("呵呵大");
e.printStackTrace();
}
System.out.println(4444);

-----------------------------------

static int aa() throws Exception{
try {
int a=4/0;
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
return 1;
}finally{
System.out.println("finally");
return 2;
}

}

輸出結果如下:

finally
2
4444

分析:雖然try中出現了運行異常java.lang.ArithmeticException,但是沒被catch捕獲到,不管程式是正常運行,還是拋異常,之前都要先調用finally(但有一次測試是先打出了異常,後輸出finally,很詫異),finally用於釋放資源,如果finally用了return,這是不規範的寫法,本不應該這麼使用,finally中的return使得本方法丟失了要跑出的異常,相當於aa方法沒有拋出異常

 

java中 異常中的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.