标签:
Java支持自己创建的异常。了解异常看这里:什么是java中的异常
方法如下:
1、所有的异常必须是Throwable的子类。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,这将产生以下结果:标签:
原文地址:http://blog.csdn.net/ooppookid/article/details/51106457