50. Divide by Zero Handling

#include <iostream>
#include <stdexcept>
using namespace std;

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

int main() {
    int a, b;
    cin >> a >> b;

    try {
        int result = divide(a, b);
        cout << "Result: " << result << "\n";
    } catch (const runtime_error& e) {
        cout << "Error: " << e.what() << "\n";
    }

    return 0;
}

Solution Details

  • If the divisor b is 0, we use throw runtime_error("Division by zero");.
  • try { ... } catch (...) allows safe handling of the exception.
  • e.what() retrieves the error message.
     

👉 In simple words:
 Instead of crashing when dividing by zero, we throw an error and catch it. The program prints "Error: Division by zero" instead of stopping.
 

Significance for Embedded Developers

  • Exceptions are rarely used in low-level embedded firmware (often disabled for performance).
  • But the concept is useful to understand: errors should be caught and handled safely rather than silently ignored.
  • Similar logic applies in validating parameters like timer prescalers or buffer sizes.
     
Loading...

Input

10 2

Expected Output

Result: 5