
CS2370 Lab 5
By:
mattfong on
May 9th, 2011 | syntax:
None | size: 2.43 KB | hits: 50 | expires: Never
//Matthew Fong
//05/09/2011
//Chapter 17 Exceptions
//Description: Shows the use of throw and catch for exceptions
//overDrawn (withdrawing more than in account)
//warningError (close to 0 balance, issue if $5 left in the account).
#include <iostream>
#include <string>
using namespace std;
void findBalance(char t, float a, float &b);
class OverDrawnError
{
private:
float balance;
string s;
public:
OverDrawnError(float b)
{
balance = b;
s = "You can't withdraw this much because you will overdraw";
}
void getOverDraw()
{
cout << "Balance: $" << balance << endl;
cout << "WARNING: " << s << endl;
}
};
class WarningError
{
private:
string s;
float balance;
public:
WarningError(float b)
{
balance = b;
s = "You will have less than $5 in your account after withdrawing";
}
void getWarning()
{
cout << "Balance: $" << balance << endl;
cout << "WARNING: " << s << endl;
}
};
int main()
{
char trans;
float amount;
char flag = 'Y';
float balance = 0.0;
do
{
cout << "Enter a transaction (W or D) and an amount: " << endl;
cin >> trans >> amount;
try
{
findBalance(trans, amount, balance);
cout << "Balance: $" << balance << endl;
}
catch(OverDrawnError o) //catches the error
{
o.getOverDraw(); //shows the balance and error
return 1;
}
catch(WarningError w) //catches the error
{
w.getWarning(); //shows the balance and the warning
//I took out the return 1 just in case the person would like to keep withdrawing
}
cout << "Would you like another transaction? Y/N" << endl;
cin >> flag;
} while(flag == 'Y' || flag == 'y');
return 0;
}
void findBalance(char t, float a, float &b)
{
if(t == 'w' || t == 'W')
{
b = b - a;
if(b <= 0) //If the balance is 0 or less
throw OverDrawnError(b); //Throws overdrawing error
if(b <= 5) //if the balance is 5 or less
throw WarningError(b); //Throws warning error
}
if(t == 'd' || t == 'D')
{
b = b + a;
}
}