1、如何定义自己的异常
Java支持自己创建的异常。了解异常看这里:什么是java中的异常
方法如下:
1、所有的异常必须是Throwable的子类。
2、如果想写一个检查异常,需要扩展Exception类。
3、如果想编写一个运行时异常,则需要扩展RuntimeException类。
4、异常类与任何其他类一样,可以包含字段和方法。
我们可以定义如下自己的异常处理类:
class MyException extends Exception{ }
例子:
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。
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程序演示调用deposit()和withdraw() 方法。
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(" Withdrawing $100..."); c.withdraw(100.00); System.out.println(" Withdrawing $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)
时间: 2024-10-12 13:34:28