Java 中的 try、catch、throw 和 throws


Java 中的 try 和 catch

方法使用 try 和 catch 關鍵字的組合來捕獲異常。try/catch 塊放置在可能生成異常的程式碼周圍。

以下是 try 和 catch 的語法:

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

catch 語句涉及宣告您嘗試捕獲的異常型別。如果在受保護的程式碼中發生異常,則檢查 try 後面的 catch 塊(或塊)。如果發生的異常型別在 catch 塊中列出,則異常將傳遞到 catch 塊,就像將引數傳遞到方法引數一樣。

示例

現在讓我們看一個實現 try 和 catch 的示例:

 線上演示

import java.io.*;
public class Demo {
   public static void main(String args[]) {
      try {
         int a[] = new int[5];
         System.out.println("Access element eighth :" + a[7]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown :" + e);
      }
      System.out.println("Out of the block");
   }
}

輸出

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 7
Out of the block

Java 中的 throw 和 throws

如果方法不處理已檢查異常,則該方法必須使用 throws 關鍵字宣告它。throws 關鍵字出現在方法簽名末尾。

您可以使用 throw 關鍵字丟擲異常,無論是新例項化的異常還是剛剛捕獲的異常。

throws 用於推遲已檢查異常的處理,而 throw 用於顯式地引發異常。

更新於: 2019年9月26日

2K+ 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告