我们什么时候应该在 Java 中创建用户定义的异常类?

javaobject oriented programmingprogramming更新于 2024/7/26 5:33:00

我们应该在 Java 中创建自己的异常。编写自己的异常类时,请牢记以下几点

  • 所有异常都必须是 Throwable 的子类。
  • 如果我们想编写由 Handle 或 Declare 规则自动执行的已检查异常,则需要扩展 Exception 类。
  • 如果我们想编写运行时异常,则需要扩展 RuntimeException 类。

我们可以定义自己的 Exception 类,如下所示:

class MyException extends Exception {
}

我们只需扩展 Exception 类即可创建自己的 Exception 类。这些被视为已检查异常。以下 InsufficientFundsException 类是用户定义的异常,它扩展了 Exception 类,使其成为已检查的异常。

示例

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

// File Name CheckingAccount.java
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;
   }
}
// File Name BankDemo.java
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();
      }
   }
}

输出

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

相关文章