python异常与C++异常处理

pro*_*eek 0 c++ exception-handling

使用以下代码,我得到了"Gotcha!" 用python.

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

我认为这是等效的C++代码,但它无法捕获该异常.

#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;
}
Run Code Online (Sandbox Code Playgroud)
Floating point exception

什么地方出了错?我怎么能抓住这个例外?

CB *_*ley 5

在C++中,除以零不会产生异常; 它会导致未定义的行为.

在实际执行除法之前,你必须检查你的除数,因为如果你真的用零除数计算一个除法表达式,就无法知道会发生什么.