Q:

Revise your program from the previous exercise to use a try block to catch the exception

0

Revise your program from the previous exercise to use a try block to catch the exception. The catch clause should print a message to the user and ask them to supply a new number and repeat the code inside the try.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <iostream>
#include <stdexcept>

int main() {
  int a, b;
  bool tryAgain;
  do {
    tryAgain = false;
    try {
      std::cin >> a >> b;
      if (b == 0)
        throw std::runtime_error("Divide by 0.");
      std::cout << a / b << std::endl;
    } catch (std::runtime_error err) {
      std::cout << err.what() << "\nTry again? (y/n)" << std::endl;
      char c;
      if (std::cin >> c && (c == 'y' || c == 'Y'))
        tryAgain = true;
    }
  } while (tryAgain);

  return 0;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now