如果我尝试在 C++ 的 catch 块中抛出某些内容,为什么会导致终止?
我有以下 C++ 代码,它给了我一个惊喜。 问题是,如果我在 catch 块内抛出除了重新抛出之外的东西, 程序将通过调用 abort 终止并在 GCC4 中给出错误消息, “抛出'int'实例后调用终止”。 如果我只使用“扔;”重新扔到 catch 块内,一切都会好起来的。
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
int main()
{
try{
throw std::string("first throw");
}
catch(std::string &x){
try{
std::cout << x << std::endl;
// throw; // if I use this line, all is fine.
throw int(2); // but if I use this line, it causes Abort() to be called
}
catch (int &k){
throw;
}
catch(...)
{
cout << "all handled here!"<< endl;
}
}
catch(...){
std::cout<< "never printed" << endl;
}
}
I have the following C++ code and it gives me a surprise.
The problem is that if I throw something except re-throw inside the catch block,
the program will be terminated by calling abort and give the error message in GCC4,
"terminate called after throwing an instance of 'int'".
If I just use "throw;" to re-throw inside the catch block, everything will be fine.
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
int main()
{
try{
throw std::string("first throw");
}
catch(std::string &x){
try{
std::cout << x << std::endl;
// throw; // if I use this line, all is fine.
throw int(2); // but if I use this line, it causes Abort() to be called
}
catch (int &k){
throw;
}
catch(...)
{
cout << "all handled here!"<< endl;
}
}
catch(...){
std::cout<< "never printed" << endl;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你抛出一个
int
,那么它不会被处理;它将被内部的 catch (int &k) 处理程序捕获,并重新抛出它;并且没有外部处理程序来捕获重新抛出的异常,因为您已经位于外部catch
块中。因此,在这种情况下,由于未处理的异常,terminate
被调用。如果您重新抛出
string
,那么它会被内部catch(...)
处理程序捕获;这不会重新抛出,因此异常已被处理。If you throw an
int
, then it won't be handled; it will be caught by the innercatch (int &k)
handler, which rethrows it; and there is no outer handler to catch the rethrown exception, since you're already in an outercatch
block. So in this case,terminate
is called due to an unhandled exception.If you rethrow the
string
, then it's caught by the innercatch(...)
handler; this doesn't rethrow, so the exception has then been handled.您的 throw 不在任何 try 处理程序内,因此它会导致调用 abort 。
这是您的代码,其中缩进已清理了一下并内嵌了一些注释:
You
throw
is not inside anytry
handler thus it leads toabort
being called.Here is your code with the indentation cleaned up a bit and some comments inline: