开发者

What type of exception is thrown when dividing by zero?

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).


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

In Windows, this generates a Structured Exception Handling exception.

See this example from MSDN:

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

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

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.

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜