A function that return a special error code is often better implemented by throwing an exception instead. This way, the error code cannot be ignored or mistake for valid data. The following class maintains an account balance.
class Account
{
private:
double balance;
public:
Account()
{
balance = 0;
}
Account(double ini ti al Deposit)
{
balance = ini ti al Deposit;
}
double getBalance()
{
return balance;
}
// returns new balance or −1 if error
double deposit(double amount)
{
if (amount > 0)
balance += amount;
else
return −1;
// Code indicating error return balance;
}
// returns new balance or −1 if invalid amount
double withdraw(double amount)
{
if ((amount > balance) || (amount<0)) return −1;
else
balance -= amount;
return balance; }
};
Rewrite the class 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.
We need at least 10 more requests to produce the solution.
0 / 10 have requested this problem solution
The more requests, the faster the answer.