开发者

The python exception vs C++ exception handling

开发者 https://www.devze.com 2023-01-04 21:04 出处:网络
With the following code, I get the \"Gotcha!\" with python. try: x = 0 y = 3/x except Exception: # ZeroDivisionError

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消