Java的異常處理

來源:互聯網
上載者:User

標籤:定義   out   應用程式   number   import   extend   虛擬機器   網路連接   osi   

以下內容引用自http://wiki.jikexueyuan.com/project/java/exceptions.html:

異常是一個程式執行過程中出現的問題。引起異常的原因包括以下幾點:

  • 使用者輸入無效的資料
  • 使用者開啟一個不能被找到的檔案
  • 網路連接已經丟失或JVM已經耗盡記憶體

一些異常是由於使用者的錯誤,也有是因為程式員的錯誤,還有是因為一些實體資源在某些形式上的錯誤。

在Java中瞭解異常處理,需要瞭解異常的三個類別:

  • 檢測異常(Checked exceptions):一個已檢測異常通常是使用者錯誤或是一個程式員不能預見的錯誤,如果一個檔案將要被開啟,但系統找不到這個檔案,異常就會發生。這些異常在編譯時間不能被簡單忽略。
  • 運行時異常(Runtime Exceptions):運行時異常是可以被程式文法避免的。不同於檢測異常,運行時異常在編譯時間可以被忽略。
  • 錯誤(Errors):這並不是異常,但這不是使用者或程式員可以控制的。錯誤經常在代碼中被忽略,因為針對一個錯誤幾乎做不了任何事。比如,如果一個堆疊溢位發生時,將會出現一個錯誤。他們在編譯時間也會被忽略。

一、異常的階層

所有的異常類都是java.lang.Exception類的子類型。異常類都是Throwable類的子類。除了異常類Error類也是由Throwable類產生的的子類。

錯誤一般不會由Java程式解決。這些條件通常是在Java程式解決不了的錯誤出現時才會發生。 Errors用來去指示那些運行時環境產生的錯誤。舉例說明:JVM(java虛擬機器)是不在記憶體中的。一般程式不能從錯誤中恢複。

Exception類含有兩個子類:IOException類和RuntimeException類。

二、異常方法

下面是Throwable類的重要方法列表。

方法 描述
public String getMessage()  返回關於發生異常的細節資訊,這些資訊在Throwable的建構函式中被初始化
public Throwable getCause()  返回傳生異常的原因,由Throwable對象來表示
public String toString()  返回與getMessage()的結果相聯絡的類的名稱
public void printStackTrace()  列印toString()跟蹤錯誤輸出資料流的棧地址的結果。
public StackTraceElement [] getStackTrace()  返回一個數組,其中包含每個元素在棧的地址。元素的索引0代表調用棧的頂部,最後一個元素表示方法調用棧的底部。
public Throwable fillInStackTrace()  用當前棧地址來填充Throwable對象的棧地址,添加到任何先前的棧地址資訊。

三、捕獲異常

一個方法用關鍵字try和catch來捕獲異常。一個try/catch塊放置在可能產生異常的代碼外。在try/catch塊內的代碼是被保護的,並且其文法如下:

try{   //Protected code}catch(ExceptionName e1){   //Catch block}

關於catch的聲明,必須要指明捕獲的異常的類型。如果受保護的代碼中發生異常,跟在try後面的catch塊會被檢測。如果異常類型在catch中出現了,那麼這個異常會被傳遞到catch當中,就像實參傳遞到方法參數當中。

樣本:

下面的例子聲明了一個含有兩個元素的數組。然後代碼試圖訪問數組的第三個元素,這將拋出一個異常。

// File Name : ExcepTest.javaimport java.io.*;public class ExcepTest{   public static void main(String args[]){      try{         int a[] = new int[2];         System.out.println("Access element three :" + a[3]);      }catch(ArrayIndexOutOfBoundsException e){         System.out.println("Exception thrown  :" + e);      }      System.out.println("Out of the block");   }}//這將產生如下的結果Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3Out of the block

四、多個catch塊

一個try塊可以有多個catch塊。多個catch塊的文法如下:

try{   //Protected code}catch(ExceptionType1 e1){   //Catch block}catch(ExceptionType2 e2){   //Catch block}catch(ExceptionType3 e3){   //Catch block}

前面的語句示範三個catch塊,但是可以在一個try後面跟任意數量的catch塊。當被保護代碼中出現異常時,異常首先會被第一個catch塊抓住,如果該異常類型在第一個catch塊中列出,便在第一個catch塊中被捕獲。如果沒有列出,便依次向下一個catch塊中去匹配,直到找到該異常類型。最後不論是否找到現有的方法都會停止執行,並且拋出異常到上一個方法的棧地址。

樣本:

下面是程式碼片段顯示如何使用多個try/catch語句。

try{   file = new FileInputStream(fileName);   x = (byte) file.read();}catch(IOException i){   i.printStackTrace();   return -1;}catch(FileNotFoundException f) //Not valid!{   f.printStackTrace();   return -1;}

五、throws/throw關鍵詞

如果一個方法不能處理檢測異常,那麼該方法必須用關鍵字throws來聲明。throws關鍵字在方法名的最後出現。

可以通過關鍵字throw來拋出一個異常或進行剛捕獲到的異常的執行個體化。

以下方法聲明它拋出RemoteException異常:

import java.io.*;public class className{   public void deposit(double amount) throws RemoteException   {      // Method implementation      throw new RemoteException();   }   //Remainder of class definition}

一個方法可以聲明拋出一個以上的異常,這些異常用逗號分隔。例如,下面的方法聲明拋出RemoteException和InsufficientFundsException :

import java.io.*;public class className{   public void withdraw(double amount) throws RemoteException, InsufficientFundsException   {       // Method implementation   }   //Remainder of class definition}

提示:throw用於拋出異常,throws用於告訴調用此方法的方法需要處理這個異常,同樣throws可以在調用的方法中不用處理,直接throws給上一層,知道給JVM去處理。

六、關鍵字finally

finally關鍵字用於建立跟在try後面的代碼塊,finally代碼塊總是會被執行的,不管是怎樣的異常發生。

使用finally塊允許運行想要執行的任何cleanup-type語句,無論在受保護的代碼中發生什麼。

finally代碼塊出現在最後一個catch塊之後並且文法如下:

try{   //Protected code}catch(ExceptionType1 e1){   //Catch block}catch(ExceptionType2 e2){   //Catch block}catch(ExceptionType3 e3){   //Catch block}finally{   //The finally block always executes.}

樣本:

public class ExcepTest{   public static void main(String args[]){      int a[] = new int[2];      try{         System.out.println("Access element three :" + a[3]);      }catch(ArrayIndexOutOfBoundsException e){         System.out.println("Exception thrown  :" + e);      }      finally{         a[0] = 6;         System.out.println("First element value: " +a[0]);         System.out.println("The finally statement is executed");      }   }}//這將產生如下結果:Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3First element value: 6The finally statement is executed

以下幾點需要注意:

  • catch在沒有try關鍵字的情況下是不能夠出現的。
  • try/catch語句塊中並不是強制出現finally塊。
  • try語句塊不能獨立存在(即沒有任何catch和finally塊)。
  • 在try/catch和finally塊之間是不能出現任何代碼的。

七、聲明自己的異常

可以在Java中建立自己的異常。編寫自己的異常類,要記住以下幾點:

  • 所有的異常必須Throwable的子類。
  • 如果想寫一個自動遵守正確處理或聲明規則的檢測異常,需要繼承Exception 類。
  • 如果想編寫一個運行時異常,需要繼承RuntimeException類。

如下可以定義自己的異常類:

class MyException extends Exception{}

只需要繼承Exception類來建立自己的異常類。這些被認為是檢測異常。以下InsufficientFundsException類是一個使用者定義的異常,同樣繼承了Exception類,成為檢測異常。一個異常類和任何其他類一樣,包含欄位和方法。

例子:

// File Name InsufficientFundsException.javaimport java.io.*;public class InsufficientFundsException extends Exception{   private double amount;   public InsufficientFundsException(double amount)   {      this.amount = amount;   }    public double getAmount()   {      return amount;   }}

為了示範使用使用者定義的異常,下面的CheckingAccount類包含一個withdraw()方法拋出了一個InsufficientFundsException異常。

// File Name CheckingAccount.javaimport java.io.*;public class CheckingAccount{   private double balance;   private int number;   public CheckingAccount(int number)   {      this.number = number;   }   public void deposit(double amount)   {      balance += amount;   }   public void withdraw(double amount) throws InsufficientFundsException   {      if(amount <= balance)      {         balance -= amount;      }      else      {         double needs = amount - balance;         throw new InsufficientFundsException(needs);      }   }   public double getBalance()   {      return balance;   }   public int getNumber()   {      return number;   }}

下面的BankDemo程式示範了調用CheckingAccount的deposit()和withdraw()方法。

// File Name BankDemo.javapublic class BankDemo{   public static void main(String [] args)   {      CheckingAccount c = new CheckingAccount(101);      System.out.println("Depositing $500...");      c.deposit(500.00);      try      {         System.out.println("\nWithdrawing $100...");         c.withdraw(100.00);         System.out.println("\nWithdrawing $600...");         c.withdraw(600.00);      }catch(InsufficientFundsException e)      {         System.out.println("Sorry, but you are short $"                                  + e.getAmount());         e.printStackTrace();      }    }}

編譯上述三個檔案並運行 BankDemo,將產生以下結果:

Depositing $500...Withdrawing $100...Withdrawing $600...Sorry, but you are short $200.0InsufficientFundsException        at CheckingAccount.withdraw(CheckingAccount.java:25)        at BankDemo.main(BankDemo.java:13)

八、常見的異常

在Java中,可以定義兩種異常和錯誤

  • JVM異常:這些異常/錯誤是由JVM在邏輯層上或專門拋出的。例如:NullPointerException,ArrayIndexOutOfBoundsException,ClassCastException。
  • 程式性異常:這些異常是由應用程式或是編寫API的程式員明確拋出的,例如:IllegalArgumentException,IllegalStateException。

 

測試工程:https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test15

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.