Java 简明教程

Java - Custom Exception

Java Custom Exception

自定义异常是指根据 exception 的需求创建一个你自己的异常来定制它。自定义异常来自 Exception 类。

Need of Java Custom Exceptions

  1. 在项目中基于不同类型的错误对异常进行分类。

  2. 为了允许应用程序级别的异常处理。

Create a Custom Exception in Java

要创建一个自定义异常,你需要创建一个 class ,它必须从 Exception 类继承。

Syntax

以下是在 Java 中创建自定义类的语法 -

class MyException extends Exception {
}

您只需扩展预定义的 Exception 类即可创建自己的 Exception。这些被认为是受检异常。

Rules to Create Custom Exception

在编写您自己的异常类时,请记住以下几点 -

  1. 所有异常都必须是 Throwable 的子类。

  2. 如果你想编写一个自动受到 Handle 或 Declare 规则强制执行的检查异常,则需要扩展 Exception 类。

  3. 如果您想编写运行时异常,则需要扩展 RuntimeException 类。

Java Custom Exception Example

以下 InsufficientFundsException 类是扩展 Exception 类的用户定义异常,使其成为受检异常。异常类与任何其他类一样,包含有用的字段和方法。

class InsufficientFundsException extends Exception {
   private double amount;

   public InsufficientFundsException(double amount) {
      this.amount = amount;
   }

   public double getAmount() {
      return amount;
   }
}

为了演示如何使用我们用户定义的异常,以下 CheckingAccount 类包含一个 withdraw() 方法,该方法会抛出一个 InsufficientFundsException。

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() 方法。

package com.tutorialspoint;

public 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();
      }
   }
}

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;
   }
}

class InsufficientFundsException extends Exception {
   private double amount;

   public InsufficientFundsException(double amount) {
      this.amount = amount;
   }

   public double getAmount() {
      return amount;
   }
}

编译以上三个文件并运行 BankDemo。这将产生以下结果:

Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
com.tutorialspoint.InsufficientFundsException
	at com.tutorialspoint.CheckingAccount.withdraw(BankDemo.java:39)
	at com.tutorialspoint.BankDemo.main(BankDemo.java:14)

在下一个示例中,我们将自定义异常声明为 RuntimeException 以使其成为未经检查的异常类,如下所示 -

class MyException extends RuntimeException {
}

Example to Create Custom Class by Extending Runtime Exception

我们正在扩展预定义的 RuntimeException 类以创建自己的 Exception 作为未经检查的异常。以下 InsufficientFundsException 类是扩展 RuntimeException 类的用户定义异常,使其成为未经检查的异常。RuntimeException 类与任何其他类一样,包含有用的字段和方法。

class InsufficientFundsException extends RuntimeException {
   private double amount;

   public InsufficientFundsException(double amount) {
      this.amount = amount;
   }

   public double getAmount() {
      return amount;
   }
}

以下 BankDemo 程序演示使用未经检查的异常调用 CheckingAccount 的 deposit() 和 withdraw() 方法。

package com.tutorialspoint;

public class BankDemo {

   public static void main(String [] args) {
      CheckingAccount c = new CheckingAccount(101);
      System.out.println("Depositing $500...");
      c.deposit(500.00);

      System.out.println("\nWithdrawing $100...");
      c.withdraw(100.00);
      System.out.println("\nWithdrawing $600...");
      c.withdraw(600.00);

   }
}

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) {
      if(amount <= balance) {
         balance -= amount;
      }else {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs);
      }
   }

   public double getBalance() {
      return balance;
   }

   public int getNumber() {
      return number;
   }
}

class InsufficientFundsException extends RuntimeException {
   private double amount;

   public InsufficientFundsException(double amount) {
      this.amount = amount;
   }

   public double getAmount() {
      return amount;
   }
}

编译并运行 BankDemo。这将产生以下结果 -

Depositing $500...

Withdrawing $100...

Withdrawing $600...
Exception in thread "main"
com.tutorialspoint.InsufficientFundsException
	at com.tutorialspoint.CheckingAccount.withdraw(BankDemo.java:35)
	at com.tutorialspoint.BankDemo.main(BankDemo.java:13)