java中checked和unchecked 異常處理

來源:互聯網
上載者:User

標籤:lang   使用   內容   bsp   stat   handle   please   關閉   ems   

有兩種類型的異常:一種是checked異常一種是unchecked異常,在這篇文章中我們將利用執行個體來學習這兩種異常,checked的異常和unchecked異常最大的區別就是checked去唱是在編譯時間檢查的而unchecked異常是在運行時檢查的。

什麼是checked異常呢?

checked異常在編譯時間檢查,這意味著如果一個方法拋出checked異常,那麼它應該使用try-catch塊或者使用throws關鍵字來處理這個異常,否則的話程式會報編譯錯誤,命名為checked異常是因為是在編譯時間checked的。

用例子來理解這個問題,在這個例子中,我們讀取myfile.txt這個檔案並且將它的內容輸出到螢幕上,在下邊這個程式中有三處異常被拋出。FileInputStream使用了指定的檔案路徑和名稱,拋出FileNotFoundException,這個讀取檔案內容的read()函數拋出IOException異常,關閉檔案輸入資料流的close()函數同樣也拋出IOException異常。

 

 
  1. import java.io.*;  
  2. class Example {    
  3.    public static void main(String args[])   
  4.    {  
  5.     FileInputStream fis = null;  
  6.     /*This constructor FileInputStream(File filename) 
  7.      * throws FileNotFoundException which is a checked 
  8.      * exception*/  
  9.         fis = new FileInputStream("B:/myfile.txt");   
  10.     int k;   
  11.   
  12.     /*Method read() of FileInputStream class also throws  
  13.      * a checked exception: IOException*/  
  14.     while(( k = fis.read() ) != -1)   
  15.     {   
  16.         System.out.print((char)k);   
  17.     }   
  18.   
  19.     /*The method close() closes the file input stream 
  20.      * It throws IOException*/  
  21.     fis.close();      
  22.    }  
  23. }  


輸出的結果:

 

 

 
  1. Exception in thread "main" java.lang.Error: Unresolved compilation problems:   
  2. Unhandled exception type FileNotFoundException  
  3. Unhandled exception type IOException  
  4. Unhandled exception type IOException  


為什麼這個會編譯錯誤呢?像我在一開始提到的checked異常在編譯時間被檢查,因為我們沒有處理這些異常,我們的編譯器報出了編譯錯誤。

 

怎麼解決這個錯誤呢?有兩種方式避免這種錯誤,我們一條一條的來看:

方法一:使用throws關鍵字聲明異常

我們知道在main()函數裡有三個checked異常發生,那麼避免這種編譯錯誤的一種方式就是:在方法上使用throws關鍵字聲明一個異常,你或許會想我們的代碼拋出FileNotFoundException和IOEXception,為什麼我們是聲明了一個IOException呢,原因是IOException是FileNotFoundException的父類,前者預設覆蓋了後者,如果你想你也可以這樣聲明異常:

 

 
  1. public static void main(String args[]) throws IOException, FileNotFoundException.  

 

 
  1. import java.io.*;  
  2. class Example {    
  3.    public static void main(String args[]) throws IOException  
  4.    {  
  5.       FileInputStream fis = null;  
  6.       fis = new FileInputStream("B:/myfile.txt");   
  7.       int k;   
  8.   
  9.       while(( k = fis.read() ) != -1)   
  10.       {   
  11.        System.out.print((char)k);   
  12.       }   
  13.       fis.close();    
  14.    }  
  15. }  


輸出結果:

 

File content is displayed on the screen.

方法二:使用try-catch塊處理異常

上一種方法並不是很好,那不是處理異常最好的方式,你應該對每一個異常給出有意義的資訊,使那些想瞭解這些錯誤的人能夠理解,下邊是這樣的代碼:

 

 
  1. import java.io.*;  
  2. class Example {    
  3.    public static void main(String args[])  
  4.    {  
  5.     FileInputStream fis = null;  
  6.     try{  
  7.         fis = new FileInputStream("B:/myfile.txt");   
  8.     }catch(FileNotFoundException fnfe){  
  9.             System.out.println("The specified file is not " +  
  10.             "present at the given path");  
  11.      }  
  12.     int k;   
  13.     try{  
  14.         while(( k = fis.read() ) != -1)   
  15.         {   
  16.         System.out.print((char)k);   
  17.         }   
  18.         fis.close();   
  19.     }catch(IOException ioe){  
  20.         System.out.println("I/O error occurred: "+ioe);  
  21.      }  
  22.    }  
  23. }  

 

 

上邊的代碼能夠正常運行,並將內容顯示出來

下邊是一些其他的checked異常

SQLException

IOEXception

DataAccessException

ClassNotFoundException

InvocationTargetException

 

什麼是unchecked異常呢

unchecked異常在編譯時間不會檢查,這意味著即使你沒有聲明或者處理異常你的程式也會拋出一個unchecked異常,程式不會給出一個編譯錯誤,大多數情況下這些異常的發生是由於使用者在互動過程中提供的壞資料。這需要程式員提前去判斷這種能夠產生這種異常的情況並且恰當的處理它。所有的unchecked異常都是RuntimeException的子類。

 

我們來看一下下邊的代碼:

 

 
  1. class Example {    
  2.    public static void main(String args[])  
  3.    {  
  4.     int num1=10;  
  5.     int num2=0;  
  6.     /*Since I‘m dividing an integer with 0 
  7.      * it should throw ArithmeticException*/  
  8.     int res=num1/num2;  
  9.     System.out.println(res);  
  10.    }  
  11. }  


如果你編譯這段代碼,這段代碼將會被通過,但是當你啟動並執行時候它將拋出ArithmeticException。這段代碼清楚的表明了unchecked異常在編譯期間是不會被checked的,他們在運行期間被檢查,我們來看另一個例子:

 

 

 
  1. class Example {    
  2.    public static void main(String args[])  
  3.    {  
  4.     int arr[] ={1,2,3,4,5};  
  5.     /*My array has only 5 elements but 
  6.      * I‘m trying to display the value of  
  7.      * 8th element. It should throw 
  8.      * ArrayIndexOutOfBoundsException*/  
  9.     System.out.println(arr[7]);  
  10.    }  
  11. }  


這段代碼同樣被成功的編譯通過,因為ArrayIndexOutOfBoundsException是unchecked異常。

 

注意:這並不意味著編譯器不檢查這些異常我們就不處理這些異常了,事實上我們需要更加小心的處理這些異常,例如在上邊的例子中,應該提供給使用者一個他想讀取的資訊在數組中不存在的資訊,以便使用者修改這個問題

 

 
  1. class Example {    
  2.     public static void main(String args[])  
  3.     {  
  4.         try{  
  5.         int arr[] ={1,2,3,4,5};  
  6.         System.out.println(arr[7]);  
  7.         }catch(ArrayIndexOutOfBoundsException e){  
  8.             System.out.println("The specified index does not exist " +  
  9.                     "in array. Please correct the error.");  
  10.         }  
  11.     }  
  12. }  


這裡還有其他的一些常見的unchecked異常:

 

NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
IllegalArgumentException

java中checked和unchecked 異常處理

聯繫我們

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