java中的異常(一)

來源:互聯網
上載者:User

標籤:nbsp   輸出   code   ati   color   dex   錯誤   pre   except   

java異常的概念

執行期的錯誤(javac xxx.java)

運行期的錯誤(java xxx)

 

這裡講的是運行期出現的錯誤

class TestEx {    public static void main(String[] args)    {     try{        int[] arr={1,2,3};        System.out.print(1);        System.out.println(arr[4]);        System.out.print(2);    }    catch(ArrayIndexOutOfBoundsException ae){        System.out.print(3);        ae.printStackTrace();    }    }}

上面這段代碼的輸出結果是3

為啥12沒列印出來呢?System.out.println(arr[4])這段帶代碼想擷取數組中的第五個元素但是沒有所以報錯了直接執行了catch中的代碼塊。也就是說一旦出錯try中的代碼就不會執行而是會執行接收這個錯誤的catch代碼塊中的代碼。

catch(ArrayIndexOutOfBoundsException ae)

這段代碼可以理解為聲明一個ArrayIndexOutOfBoundsException類型的ae變數作為catch方法的形參

在出錯時java解譯器會調用catch方法並且new出一個新的ArrayIndexOutOfBoundsException類型的執行個體然後傳給ae

 

java中的異常(一)

聯繫我們

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