本文介绍了python异常与C ++异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码,我得到Gotcha!使用python。

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


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

我认为这是等效的C ++代码,但它无法捕捉到exeption。

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?

推荐答案

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

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.

这篇关于python异常与C ++异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 03:37