Java Reference
In-Depth Information
To demonstrate using our user-defined exception, the following Checking-
Account class contains a withdraw() method that throws an InsufficientFunds-
Exception. Because this is a checked exception, it must be declared in the
signature of withdraw(). Notice that the throw keyword is used to throw an
InsufficientFundsException.
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;
}
}
The following BankDemo program demonstrates invoking the deposit()
and withdraw() methods of CheckingAccount. Notice that the deposit() method
is invoked without a try/catch block around it, whereas the withdraw() method
can be invoked only within a try/catch block. Study the program and try to
determine its output, which is shown in Figure 11.11.
Search WWH ::




Custom Search