mattfong

CS2370 Lab 5

May 9th, 2011
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. //Matthew Fong
  2. //05/09/2011
  3. //Chapter 17 Exceptions
  4. //Description: Shows the use of throw and catch for exceptions
  5. //overDrawn (withdrawing more than in account)
  6. //warningError (close to 0 balance, issue if $5 left in the account).
  7. #include <iostream>
  8. #include <string>
  9. using namespace std;
  10.  
  11. void findBalance(char t, float a, float &b);
  12.  
  13. class OverDrawnError
  14. {
  15. private:
  16. float balance;
  17. string s;
  18.  
  19. public:
  20. OverDrawnError(float b)
  21. {
  22. balance = b;
  23. s = "You can't withdraw this much because you will overdraw";
  24. }
  25.  
  26. void getOverDraw()
  27. {
  28. cout << "Balance: $" << balance << endl;
  29. cout << "WARNING: " << s << endl;
  30. }
  31. };
  32.  
  33. class WarningError
  34. {
  35. private:
  36. string s;
  37. float balance;
  38. public:
  39. WarningError(float b)
  40. {
  41. balance = b;
  42. s = "You will have less than $5 in your account after withdrawing";
  43. }
  44.  
  45. void getWarning()
  46. {
  47. cout << "Balance: $" << balance << endl;
  48. cout << "WARNING: " << s << endl;
  49. }
  50. };
  51.  
  52. int main()
  53. {
  54. char trans;
  55. float amount;
  56. char flag = 'Y';
  57. float balance = 0.0;
  58.  
  59. do
  60. {
  61. cout << "Enter a transaction (W or D) and an amount: " << endl;
  62. cin >> trans >> amount;
  63.  
  64. try
  65. {
  66. findBalance(trans, amount, balance);
  67. cout << "Balance: $" << balance << endl;
  68. }
  69. catch(OverDrawnError o) //catches the error
  70. {
  71. o.getOverDraw(); //shows the balance and error
  72. return 1;
  73. }
  74. catch(WarningError w) //catches the error
  75. {
  76. w.getWarning(); //shows the balance and the warning
  77. //I took out the return 1 just in case the person would like to keep withdrawing
  78. }
  79. cout << "Would you like another transaction? Y/N" << endl;
  80. cin >> flag;
  81. } while(flag == 'Y' || flag == 'y');
  82.  
  83. return 0;
  84. }
  85.  
  86. void findBalance(char t, float a, float &b)
  87. {
  88. if(t == 'w' || t == 'W')
  89. {
  90. b = b - a;
  91.  
  92. if(b <= 0) //If the balance is 0 or less
  93. throw OverDrawnError(b); //Throws overdrawing error
  94.  
  95. if(b <= 5) //if the balance is 5 or less
  96. throw WarningError(b); //Throws warning error
  97. }
  98.  
  99. if(t == 'd' || t == 'D')
  100. {
  101. b = b + a;
  102. }
  103. }
Advertisement
Add Comment
Please, Sign In to add comment