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());
}

If a method can throw an Execption then you need to declare it as such, eg

public void myMethod() throws Exception { ...

In your test code you are missing the "try" keyword, as in

try {
    some code
} catch ....
Member Avatar for joankim

Use an IllegalArgumentException:

throw new IllegalArgumentException("There were insufficient funds");

Please mark as solved and vote my post if this solves you problem. And I see no reason why it shouldn't.

`

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.