HOWTO · Java

在 Java 中创建用户定义的自定义异常

本教程演示如何在 Java 中创建用户定义的自定义异常。

除了 NullPointerException 或 ArithmeticException 之类的预定义异常,我们还可以在 Java 中创建用户定义的自定义异常。Throw 关键字和 try-catch 块生成自定义用户定义的异常。

本教程演示了如何在 Java 中创建自定义的用户定义异常。

Java 中的用户定义异常

预定义的 Java 异常几乎涵盖了程序中的所有异常,但有时需要创建我们的异常。用户定义的异常捕获并为预定义的 Java 异常的子集提供特定的处理。

该异常也可以是与工作流和业务逻辑相关的业务逻辑异常。要创建自定义的用户定义异常,我们必须首先了解确切的问题。

让我们尝试一个用户定义异常的示例。要创建用户定义的异常,首先,我们需要从 Java.lang 扩展 Exception 类。

例子:

package delftstack;

public class User_Defined_Exception {
  public static void main(String args[]) {
    try {
      throw new Custom_Exception(404);
    } catch (Custom_Exception e) {
      System.out.println(e);
      e.printStackTrace();
    }
  }
}
class Custom_Exception extends Exception {
  int code;
  Custom_Exception(int status_code) {
    code = status_code;
  }
  public String toString() {
    return ("This is user defined exception to show the status code: " + code);
  }
}

此代码将引发用户定义的字符串异常。

输出:

This is user defined exception to show the status code: 404
This is user defined exception to show the status code: 404
    at delftstack.User_Defined_Exception.main(User_Defined_Exception.java:6)

用于检查 Java 中 ID 有效性的用户定义异常

让我们尝试另一个更以问题为中心的示例,例如检查 ID 的有效性。

如果用户输入 ID,我们将创建一个异常。如果数据库中不存在,则抛出无效 ID 异常。

例子:

package delftstack;
import java.util.*;

class InValid_ID extends Exception {
  public InValid_ID(String ID) {
    super(ID);
  }
}
public class User_Defined_Exception {
  // Method to find ID
  static void find_ID(int input_array[], int ID) throws InValid_ID {
    boolean condition = false;
    for (int i = 0; i < input_array.length; i++) {
      if (ID == input_array[i]) {
        condition = true;
      }
    }
    if (!condition) {
      throw new InValid_ID("The ID is you Entered is InValid!");
    } else {
      System.out.println("The ID is you Entered is Valid!");
    }
  }
  public static void main(String[] args) {
    Scanner new_id = new Scanner(System.in);
    System.out.print("Enter the ID number: ");
    int ID = new_id.nextInt();
    try {
      int Input_Array[] = new int[] {123, 124, 134, 135, 145, 146};
      find_ID(Input_Array, ID);
    } catch (InValid_ID e) {
      System.out.println(e);
      e.printStackTrace();
    }
  }
}

上面的代码创建了一个无效的 ID 异常。如果用户输入了错误的 ID,它将引发异常。

无效的输出:

Enter the ID number: 133
delftstack.InValid_ID: The ID is you Entered is InValid!
delftstack.InValid_ID: The ID is you Entered is InValid!
    at delftstack.User_Defined_Exception.find_ID(User_Defined_Exception.java:19)
    at delftstack.User_Defined_Exception.main(User_Defined_Exception.java:32)

有效输出:

Enter the ID number: 145
The ID is you Entered is Valid!