我想抛出这样的异常:
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() 之外,我没有在任何其他函数中使用它。让我再测试一些,然后我会回复你!</p>
编辑3:
天哪,这太尴尬了。看起来我调用了错误的函数。以这种可耻的经历打扰你,我感到非常抱歉!
最佳答案
如果您在 try/catch block 之外使用 throw,则会调用 terminate。确保抛出的函数在 try block 中。
#include <iostream>
void myFunc()
{
throw "Throwing!";
}
int main()
{
try
{
myFunc();
}
catch(...)
{
std::cout << "Works fine.";
}
myFunc(); // Terminate gets called.
return 0;
}
关于c++ - 代码调用终止而不是抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15047136/