Home >Backend Development >C++ >How to Properly Handle Divide-by-Zero Errors in C ?
Catching Divide by Zero Exception
When attempting to divide by zero in C , it's not automatic for the compiler or runtime to throw an exception. The behavior is undefined, which means it could result in an exception or other unpredictable outcome.
In the provided code snippet:
int i = 0; cin >> i; try { i = 5/i; } catch (std::logic_error e) { cerr << e.what(); }
The code will not catch any exceptions when attempting to divide by zero because integer divide by zero is not considered an exception in standard C .
To handle this, you need to manually check for the divide by zero condition and throw an exception accordingly. The C standard does not explicitly define an exception for divide by zero, so you can choose to throw an exception such as:
Here's a modified code snippet that demonstrates throwing a divide by zero exception:
int intDivEx(int numerator, int denominator) { if (denominator == 0) throw std::overflow_error("Divide by zero exception"); return numerator / denominator; } try { i = intDivEx(5, 0); // Will throw an overflow_error exception } catch (std::overflow_error &e) { cerr << e.what() << endl; }
In this example, the intDivEx function checks for divide by zero and throws an std::overflow_error exception if encountered. This allows you to handle the exception in your code.
The above is the detailed content of How to Properly Handle Divide-by-Zero Errors in C ?. For more information, please follow other related articles on the PHP Chinese website!