代码调用终止而不是抛出异常

时间:2013-02-23 23:56:07

标签: c++ exception ubuntu-12.04 terminate

我想抛出这样的例外:

if (...) {  
    throw "not found";  
}

并像这样抓住它:

try {  
    myfunction();  
} catch (const char * msg) {  
    cout << msg << endl;  
}

然后它说

terminate called after throwing an instance of 'char const*'

为什么呼叫终止而不是抛出“未找到”?

编辑:

我把它更改为:

try {
    throw "not found";
} catch (const char * msg) {
    cout << "test" << endl;
} catch(...) {
    cout << "test" << endl;
}

我得到同样的错误!

EDIT2: 当我不打电话给上面的具体方法时,它的工作原理!但我不明白这个方法与异常有什么关系,我没有在上面提到的myfunction()之外的任何其他函数中使用它。让我再测试一下,然后我会回复你!<​​/ p>

EDIT3:

哦,我的,这很尴尬。看起来我调用了错误的功能。我很遗憾因为这种可耻的经历而困扰你!

1 个答案:

答案 0 :(得分:1)

如果在try / catch块之外使用throw,则会调用terminate。确保抛出的函数位于try块中。

#include <iostream>

void myFunc()
{
    throw "Throwing!";
}

int main()
{
    try
    {
        myFunc();
    }
    catch(...)
    {
        std::cout << "Works fine.";
    }

    myFunc(); // Terminate gets called.

    return 0;

}
相关问题