2. A method that returns a special error code is usually better accomplished by throwing an exceptionn
Question:
2. A method that returns a special error code is usually better accomplished by throwing an exceptionn
instead. The following class maintains an account balance.n
class Accountn
{n
private double balance;n
public Account()n
{n
balance = 0;n
}n
public Account( double initialDeposit)n
{n
balance = initialDeposit;n
}n
public double getBalance()n
{n
return balance;n
}n
// returns new balance or -1 if errorn
public double deposit( double amount)n
{n
if (amount > 0)n
balance += amount;n
elsen
return -1;// Code indicating errorn
return balance;n
}n
// returns new balance or -1 if invalid amountn
public double withdraw(double amount)n
{n
if ((amount > balance) || (amount < 0))n
return -1;n
elsen
balance -= amount;n
return balance;n
}n
}n
Rewrite the class so that it throws appropriate exceptions instead of returning −1 as an errorn
code. Write test code that attempts to withdraw and deposit invalid amounts and catches then
exceptions that are thrown.
Financial Accounting
ISBN: 978-0324645576
10th edition
Authors: W. Steve Albrecht, James D. Stice, Earl K. Stice