在C ++中使用Exception基类会导致应用程序崩溃

时间:2015-01-19 11:25:24

标签: c++ exception visual-c++ exception-handling throw

在下面的代码片段中,为什么如果我将catch语句包含在“异常基类中我得到应用程序崩溃”(附上崩溃的图像)。

但如果我使用

  

“const char * msg”

在catch()中它可以正常工作。

为什么异常基类导致应用程序崩溃?

double division(int a, int b)
{
    if (b == 0)
    {
        throw "Division by zero condition!";
    }
    return (a / b);
}
main()
{
    int x = 50;
        int y = 0;
        double z = 0;

        try {
            z = division(x, y);
            cout << "after division func" << endl;
            cout << z << endl;
        }
        catch (const char* msg) {  // WORKS FINE
        //catch (exception& err) {  // CAUSES the APP to crash![enter image description here][1]

            cout << "INside catch for divide by 0" << endl;
        }

enter image description here

2 个答案:

答案 0 :(得分:1)

除零条件不是由std :: exception

派生的

您可以做的一个解决方法是在代码中定义catch all语句

try {
            z = division(x, y);
            cout << "after division func" << endl;
            cout << z << endl;
    }

        catch (exception& err) {  // CAUSES the APP to crash![enter image description here][1]

            cout << "INside catch for divide by 0" << endl;
        }

        catch(...)    //include this in your code
        {
            cout<<"other exception occured";
        }

请参阅此处http://ideone.com/TLukAp

答案 1 :(得分:1)

在这里你要抛出一个字符串文字:

throw "Division by zero condition!";

可以通过以下方式获取:

catch (const char* msg)

但是,此异常并非来自类std::exception。如果您想要一个可以提供错误消息的消息,请使用std::runtime_error

throw std::runtime_error("Division by zero condition!");
...
catch (std::exception& err)