我们应该在Java中创建自己的异常。在编写我们自己的异常类时,请记住以下几点
所有异常都必须是Throwable的子级。
如果我们要编写一个由Handle或Delare Rule自动执行的检查异常,则需要扩展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; } } //文件名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; } } //文件名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)