除以零时抛出什么类型的异常? [英] What type of exception is thrown when dividing by zero?

查看:174
本文介绍了除以零时抛出什么类型的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当有零除错时会抛出什么异常?我尝试使用catch-all catch(...),但Visual Studio仍然抱怨有一个未处理的异常。

What kind of exception is thrown when there's a divide by zero error? I tried using the "catch-all" catch(...), but Visual Studio still complains that there's an unhandled exception.

int a = 0;
try
{
    a /= a;
}
catch (/* what should I catch?*/)
{
    cout << "divide by zero error" << endl;
}



注意:我不是在问如何防止这种类型的问题之前 -

Note: I'm not asking how to prevent this type of problem before-hand (e.g. checking if a is zero before trying to divide by zero).

推荐答案

这不是一个C ++问题,因为在标准C ++中无法这样做。

This is not a C++ question, because there is no way to do so in standard C++.

在Windows中,这会生成结构化异常处理异常。

In Windows, this generates a Structured Exception Handling exception.

请参阅此示例

__try 
{ 
    *pResult = dividend / divisor; 
} 
__except(GetExceptionCode() == EXCEPTION_INT_DIVIDE_BY_ZERO ? 
         EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{ 
    return FALSE;
}

这是非便携式的,特定于Windows。最后我知道GCC也不支持它,即使在Windows上。

This is non-portable and specific to Windows, though. Last I knew GCC doesn't support it either, even on Windows.

如果你问一个更广泛的问题,它的工作方式是你的CPU会产生一个中断当你除以零。 Windows内核处理这个并将其传递给您的进程,让您有机会处理它。如果你不处理它,你的进程死了。在Unix类型操作系统上,同样会保留,但它可能会导致一个信号。我不知道是哪一个。

In case you are asking a broader question, the way it works is your CPU will generate an interrupt when you do a divide by zero. The Windows kernel handles this and delivers it to your process, giving you an opportunity to handle it. If you don't handle it your process dies. On Unix type OSs the same will hold, but it will probably result in a signal. I am not sure which one.

我会说如果你想写可移植的C ++代码,最好是在软件中检查除以零,而不是依靠硬件生成故障,并让操作系统内核通过一些非便携式机制将它传递给您。

I would say if you want to write portable C++ code it's probably better to check for divide by zero in software rather than rely on hardware to generate a fault and for the OS kernel to deliver it to you via some non-portable mechanism.

这篇关于除以零时抛出什么类型的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆