声明自定义异常在 Java 中你可以自定义异常。编写自己的异常类时需要记住下面的几点。
可以像下面这样定义自己的异常类: class MyException extends Exception{ }
只继承 Exception 类来创建的异常类是检查性异常类。 下面的 InsufficientFundsException 类是用户定义的异常类,它继承自 Exception。 一个异常类和其它任何类一样,包含有变量和方法。 实例// 文件名InsufficientFundsException.java import java.io.*;
public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } }
为了展示如何使用我们自定义的异常类, 在下面的 CheckingAccount 类中包含一个 withdraw() 方法抛出一个 InsufficientFundsException 异常。 // 文件名称 CheckingAccount.java import java.io.*;
public 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() 方法。 //文件名称 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(); } } }
编译上面三个文件,并运行程序 BankDemo,得到结果如下所示: Depositing $500...
Withdrawing $100...
Withdrawing $600... Sorry, but you are short $200.0 InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13)
|