error3.cpp 944 B

12345678910111213141516171819202122232425262728293031323334
  1. // error3.cpp -- using an exception
  2. #include <iostream>
  3. double hmean(double a, double b);
  4. int main()
  5. {
  6. double x, y, z;
  7. std::cout << "Enter two numbers: ";
  8. while (std::cin >> x >> y)
  9. {
  10. try { // start of try block
  11. z = hmean(x,y);
  12. } // end of try block
  13. catch (const char * s) // start of exception handler
  14. {
  15. std::cout << s << std::endl;
  16. std::cout << "Enter a new pair of numbers: ";
  17. continue;
  18. } // end of handler
  19. std::cout << "Harmonic mean of " << x << " and " << y
  20. << " is " << z << std::endl;
  21. std::cout << "Enter next set of numbers <q to quit>: ";
  22. }
  23. std::cout << "Bye!\n";
  24. return 0;
  25. }
  26. double hmean(double a, double b)
  27. {
  28. if (a == -b)
  29. throw "bad hmean() arguments: a = -b not allowed";
  30. return 2.0 * a * b / (a + b);
  31. }