The python exception vs C++ exception handling

孤街浪徒 提交于 2019-12-13 03:01:01

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/3113904/the-python-exception-vs-c-exception-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!