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
Input
17 5
Output
3
Input
4 0
Output
error
Hint
- if (b == 0) throw std::runtime_error("div0");
- 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.