views:

153

answers:

3

Hi, I'm trying to catch dividing by zero attempt:

int _tmain(int argc, _TCHAR* argv[])
{
int a = 5;
try
{
int b = a / 0;
}
catch(const exception& e)
{
 cerr << e.what();
}
catch(...)
{
 cerr << "Unknown error.";
}
 cin.get();
return 0;
}

and basically it doesn't work. Any advice why? Thank you. P.S. Any chance that in the future code can be placed between [code][/code] tags instead of four spaces?

+7  A: 

Divide by zero does not raise any exceptions in Standard C++, instead it gives you undefined behaviour. Typically, if you want to raise an exception you need to do it yourself:

int divide( int a, int b ) {
   if ( b == 0 ) {
      throw DivideByZero;    // or whatever
   }
   return a / b;
}
anon
Thanks guys.P.S. Is there any reason why comment has to be at least 15 char long?
There is nothing we can do
Pseudo Spam Prevention apparently...
NoCanDo
Personally I'd make that a template, and call it checked_divide.
Steve Jessop
+2  A: 

The best way would be to check if the divisor equals 0.

C++ doesn't check divide-by-zero. A brief discussion can be found here.

Daniel Daranas
interesting though, atch reports that he got no exception thrown, which is not concurrent with your link... hmm
jpinto3912
the discussion says that the hardware *might* throw exception, not that it definitely throws one. The approach shows how to test this.
larsm
+2  A: 

You appear to be currently writing code for Windows (evidence: _tmain and _TCHAR are not portable C++).

If you would like a solution which only works on Windows, then you can use so-called "structured exception handling" (SEH):

However, this is a MS-only feature. If you rely on an exception being thrown to deal with this error, then it will take considerable effort to change your code later if you want it to work on other platforms.

It's better to write your code with an awareness of when the divisor might be 0 (just as when you do mathematics, and divide by a quantity, you must consider whether it might be 0). Neil's approach is a good low-impact solution for this: you can use his divide function whenever you aren't sure.

Steve Jessop