What does msvc 6 throw when an integer divide by z

2020-05-03 05:53发布

问题:

I have been doing a bit of experimenting, and have discovered that an exception is being thrown, when an integer divide by zero occurs.

#include <iostream>
#include <stdexcept>

using namespace std;


int main
(
    void 
)
{
    try
    {
        int x = 3;
        int y = 0;
        int z = x / y;
        cout << "Didn't throw or signal" << endl;
    }
    catch (std::exception &e)
    {
        cout << "Caught exception " << e.what() << endl;
    }

    return 0;
}

Clearly it is not throwing a std::exception. What else might it be throwing?

回答1:

It's a Windows structured exception, which has nothing to do with C++ - you would get the same exception if it were a C program.



回答2:

This article claims to have a way to convert a structured exception to a C++ exception using the _set_se_translator function.

http://www.codeproject.com/KB/cpp/seexception.aspx



回答3:

The result is undefined, you could use __try / __except block to catch the error (structured exception handling). However, why not simply check for the error before your division?



回答4:

In msvc6 you can catch it with catch(...) and rethrow it with throw; however since you can't detect exception type that way you're better off doing something else.