Handling Divide by Zero Exception
Integers in C lack native exception support. So, in the code snippet provided:
int i = 0; cin >> i; // Input might be zero try { i = 5/i; } catch (std::logic_error e) { cerr << e.what(); }
when the input is zero, it will result in undefined behavior rather than triggering an exception. To handle such scenarios, you need to perform the check and throw an exception explicitly.
In the following code, we handle division by zero exceptions using the intDivEx method:
#include <iostream> #include <stdexcept> inline int intDivEx(int numerator, int denominator) { if (denominator == 0) throw std::overflow_error("Divide by zero exception"); return numerator / denominator; } int main() { int i = 42; try { i = intDivEx(10, 0); } catch (std::overflow_error &e) { std::cout << e.what() << " -> "; } std::cout << i << std::endl; try { i = intDivEx(10, 2); } catch (std::overflow_error &e) { std::cout << e.what() << " -> "; } std::cout << i << std::endl; return 0; }
This code checks for division by zero before performing the operation. If an exception occurs, it prints an error message. Otherwise, it continues the execution.
The above is the detailed content of How to Gracefully Handle Divide-by-Zero Exceptions in C ?. For more information, please follow other related articles on the PHP Chinese website!