C++: Division with exceptions

Write double divide(double a, double b) that throws a runtime_error with the message division by zero when b is 0. For each pair of numbers, print the result, or catch the exception and print error: followed by its message.

What to build

A division function that throws an exception for a zero divisor.

Requirements

  • Throw runtime_error("division by zero") when the divisor is 0.
  • Call it inside a try block.
  • Catch by const exception& and print error: followed by the message.

Input

The first line has q (1 ≤ q ≤ 100). Each of the next q lines has two whole numbers a b.

Output

One line per pair: the quotient (printed with cout <<), or error: division by zero.

Constraints

1 ≤ q ≤ 100, and the numbers are whole.

Example

Input:

3
10 4
1 0
9 3

Output:

2.5
error: division by zero
3

Why it works

The throw leaves divide at once, so no wrong value is ever returned, and the catch lets the program carry on with the next pair.

Examples

Example 1 · Input
3
10 4
1 0
9 3
Expected output
2.5
error: division by zero
3
Example 2 · Input
1
0 5
Expected output
0

Hints

Hint 1

In divide, throw runtime_error("division by zero") when b is 0.

Hint 2

Put the call inside try { ... } and catch (const exception& e).

Hint 3

Print error: followed by e.what().

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <stdexcept>
using namespace std;

double divide(double a, double b) {
    if (b == 0) throw runtime_error("division by zero");
    return a / b;
}

int main() {
    int q;
    cin >> q;
    for (int i = 0; i < q; i++) {
        double a, b;
        cin >> a >> b;
        try {
            cout << divide(a, b) << endl;
        } catch (const exception& e) {
            cout << "error: " << e.what() << endl;
        }
    }
    return 0;
}

Lesson: Exceptions →