How to catch this error? [C++]

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?

Upvotes: 2

Views: 310

Answers (3)

Steve Jessop
Steve Jessop

Reputation: 279285

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.

Upvotes: 2

Daniel Daranas
Daniel Daranas

Reputation: 22624

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.

Upvotes: 2

anon
anon

Reputation:

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;
}

Upvotes: 7

Related Questions