1

I have the following code which should throw a division by zero exception while running. It seems that the exception is not be caught at all. I am using catch(...) to catch any exception from the try block. Is catch(...) a good approach to catch any exceptions from the try block??

try
{
    printf("Try Block");
    for (int i = 0; i < 10; i++)
    {
        printf("%d\n", 1 / i);
    }       
}

catch (...)
{
    printf("Division by zero");
}
Ajit
  • 261
  • 3
  • 15
  • 1
    No, it should not necessarily throw. If it does, that's due to the undefined behaviour, and catching it and continuing on will likely bring only pain. โ€“ chris Mar 25 '15 at 14:02
  • 3
    Division by zero is not a standard C++ exception. โ€“ molbdnilo Mar 25 '15 at 14:04
  • This was just an example to catch any exceptions within the try block. โ€“ Ajit Mar 25 '15 at 14:08

3 Answers3

2

You can't rely on the behaviour of division by zero; it's undefined:

N4296 ยง5/4:

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
0

If you need to make sure an exception is thrown when you try to divide by zero, you'll have to make your own wrapper that does it:

long double Divide(long double numerator, long double denominator)
{
  if (denominator == 0)
  {
    throw std::range_error("Division by zero!");
  }
  return numerator / denominator;
}
Bill
  • 14,257
  • 4
  • 43
  • 55
0

If you want portable code that handles divide by zero by throwing an exception, then you could write a class that wraps a suitable numeric type and checks before divide and mod operations, and use it instead of the inbuilt numeric types.... The C++ library does not provide such a type. In reality, it's not particularly useful - you can just check in your code in the specific places that might do a division or mod operation with 0.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252