C++ bootcamp · Lab 30

Safe division

mediumExceptions12 minLesson: Exceptions

Read the question, write C++ on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read two integers a and b. Print the integer division a / b.

If b is 0, catch the problem and print error instead of crashing. Throw std::runtime_error (or check b and throw) so you practise try / catch.

Input. Two integers a and b.

Output. The integer quotient, or error.

Examples

Example 1
Input
17 5
Output
3
Example 2
Input
4 0
Output
error
Hint
  1. if (b == 0) throw std::runtime_error("div0");
  2. catch (const std::exception&) { std::cout << "error\n"; }
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>
#include <stdexcept>

int main() {
  int a, b;
  std::cin >> a >> b;
  try {
    if (b == 0) throw std::runtime_error("div0");
    std::cout << a / b << "\n";
  } catch (const std::exception&) {
    std::cout << "error\n";
  }
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.