Java 中程式設計師如何手動丟擲異常?


異常是在程式執行期間發生的錯誤(執行時錯誤)。當發生異常時,程式會突然終止,並且異常行之後的程式碼將不再執行。

示例

import java.util.Scanner;
public class ExceptionExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number: ");
      int a = sc.nextInt();
      System.out.println("Enter second number: ");
      int b = sc.nextInt();
      int c = a/b;
      System.out.println("The result is: "+c);
   }
}

輸出

Enter first number:
100
Enter second number:
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:10)

手動丟擲異常

您可以使用 *throw* 關鍵字顯式地丟擲一個使用者定義的異常或預定義的異常。

異常有兩種型別:使用者定義和預定義,每個異常都由一個類表示,該類繼承自 Throwable 類。

要顯式丟擲異常,您需要例項化該類的物件,並使用 throw 關鍵字丟擲該物件。

示例

以下 Java 程式丟擲 NullPointerException 異常

public class ExceptionExample {
   public static void main(String[] args) {
      System.out.println("Hello");
      NullPointerException nullPointer = new NullPointerException();
      throw nullPointer;
   }
}

輸出

Hello
Exception in thread "main" java.lang.NullPointerException
   at MyPackage.ExceptionExample.main(ExceptionExample.java:6)

每當您顯式丟擲異常時,您都需要確保包含 throw 關鍵字的行是程式的最後一行。這是因為在它之後編寫的任何程式碼都是不可達程式碼,如果在此行下面仍然有程式碼片段,則會生成編譯時錯誤。

示例

public class ExceptionExample {
   public static void main(String[] args) {
      System.out.println("Hello");
      NullPointerException nullPointer = new NullPointerException();
      throw nullPointer;
      System.out.println("How are you");
   }
}

編譯時錯誤

D:\>javac ExceptionExample.java
ExceptionExample.java:6: error: unreachable statement
   System.out.println("How are you");
   ^
1 error

使用者定義異常

通常,throw 關鍵字主要用於丟擲使用者定義的異常。每當您需要定義自己的異常時,您都需要定義一個擴充套件 Throwable 類的類,並覆蓋所需的方法。

例項化此類,並在您希望丟擲異常的任何位置使用 throw 關鍵字丟擲它。

示例

在以下 Java 程式中,我們建立了一個名為 AgeDoesnotMatchException 的自定義異常類。

public class AgeDoesnotMatchException extends Exception{
   AgeDoesnotMatchException(String msg){
      super(msg);
   }
}

另一個類 Student 包含兩個私有變數 name、age 和一個引數化建構函式,用於初始化例項變數。

從 main 方法中,我們從使用者那裡接受 name 和 age 值,並透過傳遞接受的值來初始化 Student 類。

在 Student 類的建構函式中,我們建立了一個異常 **AgeDoesnotMatchException** 的物件,並在 age 值介於 17 和 24 之間時引發異常(使用 throws)。

public class Student extends RuntimeException {
   private String name;
   private int age;
   public Student(String name, int age){
      try {
         if (age<17||age>24) {
            String msg = "Age is not between 17 and 24";
            AgeDoesnotMatchException ex = new AgeDoesnotMatchException(msg);
            throw ex;
         }
      }catch(AgeDoesnotMatchException e) {
         e.printStackTrace();
      }
      this.name = name;
      this.age = age;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      Scanner sc= new Scanner(System.in);
      System.out.println("Enter the name of the Student: ");
      String name = sc.next();
      System.out.println("Enter the age of the Student should be 17 to 24 (including 17 and 24): ");
      int age = sc.nextInt();
      Student obj = new Student(name, age);
      obj.display();
   }
}

輸出

執行此程式時,您需要從鍵盤傳遞 name 和 age 值。如果給定的 age 值不在 17 和 24 之間,則會發生異常,如下所示:

Enter the name of the Student:
Krishna
Enter the age of the Student should be 17 to 24 (including 17 and 24):
14
AgeDoesnotMatchException: Age is not between 17 and 24
Name of the Student: Krishna'
Age of the Student: 14
   at Student.<init>(Student.java:18)
   at Student.main(Student.java:39)

更新於: 2020年7月2日

5K+ 瀏覽量

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告