error5.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. //error5.cpp -- unwinding the stack
  2. #include <iostream>
  3. #include <cmath> // or math.h, unix users may need -lm flag
  4. #include <string>
  5. #include "exc_mean.h"
  6. class demo
  7. {
  8. private:
  9. std::string word;
  10. public:
  11. demo (const std::string & str)
  12. {
  13. word = str;
  14. std::cout << "demo " << word << " created\n";
  15. }
  16. ~demo()
  17. {
  18. std::cout << "demo " << word << " destroyed\n";
  19. }
  20. void show() const
  21. {
  22. std::cout << "demo " << word << " lives!\n";
  23. }
  24. };
  25. // function prototypes
  26. double hmean(double a, double b);
  27. double gmean(double a, double b);
  28. double means(double a, double b);
  29. int main()
  30. {
  31. using std::cout;
  32. using std::cin;
  33. using std::endl;
  34. double x, y, z;
  35. {
  36. demo d1("found in block in main()");
  37. cout << "Enter two numbers: ";
  38. while (cin >> x >> y)
  39. {
  40. try { // start of try block
  41. z = means(x,y);
  42. cout << "The mean mean of " << x << " and " << y
  43. << " is " << z << endl;
  44. cout << "Enter next pair: ";
  45. } // end of try block
  46. catch (bad_hmean & bg) // start of catch block
  47. {
  48. bg.mesg();
  49. cout << "Try again.\n";
  50. continue;
  51. }
  52. catch (bad_gmean & hg)
  53. {
  54. cout << hg.mesg();
  55. cout << "Values used: " << hg.v1 << ", "
  56. << hg.v2 << endl;
  57. cout << "Sorry, you don't get to play any more.\n";
  58. break;
  59. } // end of catch block
  60. }
  61. d1.show();
  62. }
  63. cout << "Bye!\n";
  64. // cin.get();
  65. // cin.get();
  66. return 0;
  67. }
  68. double hmean(double a, double b)
  69. {
  70. if (a == -b)
  71. throw bad_hmean(a,b);
  72. return 2.0 * a * b / (a + b);
  73. }
  74. double gmean(double a, double b)
  75. {
  76. if (a < 0 || b < 0)
  77. throw bad_gmean(a,b);
  78. return std::sqrt(a * b);
  79. }
  80. double means(double a, double b)
  81. {
  82. double am, hm, gm;
  83. demo d2("found in means()");
  84. am = (a + b) / 2.0; // arithmetic mean
  85. try
  86. {
  87. hm = hmean(a,b);
  88. gm = gmean(a,b);
  89. }
  90. catch (bad_hmean & bg) // start of catch block
  91. {
  92. bg.mesg();
  93. std::cout << "Caught in means()\n";
  94. throw; // rethrows the exception
  95. }
  96. d2.show();
  97. return (am + hm + gm) / 3.0;
  98. }