Java基礎:異常捕獲順序,java捕獲順序

來源:互聯網
上載者:User

Java基礎:異常捕獲順序,java捕獲順序

 轉載請註明出處:jiq•欽's technical Blog 

public voidtestException(){int a[] = {1,2,3};int q = 0;try{for(int i=0;i<a.length;i++){a[i] /= q;}}catch(ArithmeticException h){System.out.print("ArithmeticException\n");        //執行}catch(Exception e){System.out.print("Exception\n");        //不會執行,且必須放在ArithmeticException後面/** * 範圍更大的Exception不但必須放在後面 * 而且放在後面還不會被執行(被前面的範圍更小的 * 異常攔截了),那這樣還有什意義呢??? */}finally{System.out.print("finally\n");}}//<span style="color:#3333ff;">output</span>ArithmeticExceptionfinally

 *        要點1:雖然ArithmeticException繼承自Exception,但是當發生ArithmeticException異常

 *                        並捕獲的時候,就只會捕獲實際發生的這個異常,並不會因為Exception是其父類而

 *                        執行Exception那個catch子句。

 *        要點2:但是如果你嘗試將範圍更大的Exception的catch語句放到的catch語句的前面,那麼就會發生

 *                        catch子句不可到達的錯誤“Unreachablecatch block for ArithmeticException.

 *                        Itis already handled by the catch block for Exception”

 *                        即範圍更大的異常(父類)必須放在後面,如果沒有繼承關係,比如ClassNotFoundException,

 *                        和ArithmeticException的catch子句之間就無所謂先後關係。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.