What I'm supposed to do: Rewrite the class below, so that it throws appropriate exceptions instead of returning -1 as an error code. Write test code that attempts to withdraw and deposit invalid amounts and catches the exceptions that are thrown.
Original code:
class Account
{
private double balance;
public Account()
{
balance = 0;
}
public Account(double initialDeposit)
{
balance = initialDeposit;
}
public double getBalance()
{
return balance;
} //Returns new balance or -1 if error.
public double deposit(double amount)
{
if (amount > 0)
balance += amount;
else
return -1;
return balance;
}
public double withdraw(double amount)
{
if ((amount > balance) || (amount < 0))
return -1;
else
balance -= amount;
return balance;
}
}
New code:
class Account
{
private double balance;
public Account()
{
balance = 0;
}
public Account(double initialDeposit)
{
balance = initialDeposit;
}
public double getBalance()
{
return balance;
} //Returns new balance or -1 if error.
public double deposit(double amount)
{
if (amount > 0)
balance += amount;
else
return -1;
return balance;
}
public double withdraw(double amount)
{
if ( (balance - amount) < 0 ) {
//instead of return -1 do
throw new Exception ("There were insufficient funds");
else
return balance;
}
}
}
I'm getting an error with the else at the end and also I know I need to add something similar to this to main, but I just can't seem to put it together right.
{
myAccount.withdraw(100.00);
}
catch(Exception e)
{
System.err.println(e.getMessage());
}