gpt4 book ai didi

c++ - 如果我尝试在 C++ 中的 catch block 中抛出一些东西,为什么会导致终止

转载 作者:可可西里 更新时间:2023-11-01 15:40:18 26 4
gpt4 key购买 nike

我有以下 C++ 代码,它给了我一个惊喜。问题是,如果我在 catch block 中抛出除了重新抛出之外的东西,程序将通过调用 abort 终止并在 GCC4 中给出错误消息,“在抛出'int'实例后调用终止”。如果我只使用“抛出;”重新扔进 catch block ,一切都会好起来的。

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

最佳答案

如果你抛出一个int,那么它不会被处理;它将被内部的 catch (int &k) 处理程序捕获,并重新抛出它;并且没有外部处理程序来捕获重新抛出的异常,因为您已经在外部 catch block 中。因此在这种情况下,terminate 由于未处理的异常而被调用。

如果您重新抛出 string,那么它会被内部 catch(...) 处理程序捕获;这不会重新抛出,因此异常已被处理。

关于c++ - 如果我尝试在 C++ 中的 catch block 中抛出一些东西,为什么会导致终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8975214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com