Reputation: 9
I am trying to use the exceptions catching mechanism on a simple piece of C++ code that does on purpose a division by 0:
#include <iostream>
using namespace std;
const int DefaultSize = 10;
int main()
{
int top = 90;
int bottom = 0;
cout << "top / 2 = " << (top/ 2) << endl;
cout << "top / 3 = " << (top/ 3) << endl;
try
{
cout << "top divided by bottom = ";
cout << (top / bottom) << endl;
}
catch(...)
{
cout << "something has gone wrong!" << endl;
}
cout << "Done." << endl;
return 0;
}
The program crashes and doesn't execute the catch block - In Eclipse I am getting a standard error:
0 [main] CPP166 8964 cygwin_exception::open_stackdumpfile: Dumping stack trace to CPP166.exe.stackdump.
Run the program in another IDE NetBeans and have done multiple clen and re-built with no positive results.
Please help I have looked at the related answers but I cannot identify the problem.
Upvotes: 1
Views: 834
Reputation: 881263
Division by zero is not one of the events that raises an exception in C++.
The exceptions listed in the ISO standard are:
namespace std {
class logic_error;
class domain_error;
class invalid_argument;
class length_error;
class out_of_range;
class runtime_error;
class range_error;
class overflow_error;
class underflow_error;
}
and you would think that overflow_error
would be ideal for indicating a divide by zero.
But C++03
and C++11
section 5.6 /4
specifically state:
If the second operand of
/
or%
is zero, the behavior is undefined.
If you want an exception, you will have to code it yourself, with something like:
#include <stdexcept>
inline int intDiv (int num, int denom) {
if (denom == 0) throw std::overflow_error("DivByZero");
return num / denom;
}
and convert your calls from:
cout << (top / bottom) << endl;
to:
cout << intDiv(top, bottom) << endl;
Upvotes: 2