【问题标题】:Code calls terminate instead of throwing exception代码调用终止而不是抛出异常
【发布时间】:2013-02-09 10:13:21
【问题描述】:

我想抛出这样的异常:

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;
}

我得到同样的错误!

编辑2: 当我不调用上面的特定方法时,它可以工作!但是我不明白这个方法与异常有什么关系,除了上面提到的myfunction()之外,我没有在任何其他函数中使用它。让我再测试一下,然后我会回复你的!

EDIT3:

哦,天哪,这很尴尬。看起来我调用了错误的函数。很抱歉以这种可耻的经历打扰您!

【问题讨论】:

  • @ta.speot.is: 什么不是什么?
  • @BastianMattes:你能展示你的真实代码吗?
  • 使用调试器找出来
  • 对不起,伙计们,我看到 const 不在同一个地方,并被 constconst * 与 Scott Meyers 所说的了解两者之间的区别搞糊涂了。
  • @BastianMattes liveworkspace.org/code/3Z0gVd$8 try 之前,您是否可能在try 块之外调用myfunction()

标签: c++ exception ubuntu-12.04 terminate


【解决方案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;

}

【讨论】:

  • 看我上面的编辑,我肯定是在 try 块里面。
猜你喜欢
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
  • 2012-03-19
  • 1970-01-01
相关资源
最近更新 更多