1

With the following code, I get the "Gotcha!" with python.

try:
    x = 0
    y = 3/x
except Exception:
    # ZeroDivisionError
    print "Gotcha!"

I think this is the equivalent C++ code, but it can't catch the exeption.

#include <iostream>

int main()
{
  int x = 0;
  //float y = 3.0/x;
  int z = 0;

  try {
      z = 3 / x;
  } catch (std::exception) {
      std::cout << "Gotcha!";
  }

  std::cout << z;
}
Floating point exception

What went wrong? How can I catch this exception?

prosseek
  • 182,215
  • 215
  • 566
  • 871
  • 1
    Related: [How do I catch system-level exceptions in Linux C++?](http://stackoverflow.com/questions/618215/how-do-i-catch-system-level-exceptions-in-linux-c) – miku Jun 24 '10 at 21:14
  • For a Windows specific perspective see this question: http://stackoverflow.com/questions/1909967/what-does-msvc-6-throw-when-an-integer-divide-by-zero-occurs – Mark Ransom Jun 24 '10 at 21:16

1 Answers1

5

In C++, dividing by zero doesn't generate an exception; it causes undefined behaviour.

You must check you divisor before actually performing the division, as there is no way to know what will happen if you do actually evaluate a division expression with a zero divisor.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656