CS *_*Pei 10 c++ exception try-catch throw gcc4
我有以下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;
}
}
Run Code Online (Sandbox Code Playgroud)
Mik*_*our 13
如果你扔了int,那么就不会被处理; 它会被内部catch (int &k)处理程序捕获,它会重新抛出它; 并且没有外部处理程序来捕获重新抛出的异常,因为您已经在外部catch块中.所以在这种情况下,terminate由于未处理的异常而被调用.
如果你重新抛出string,那么它被内部catch(...)处理程序捕获; 这不会重新抛出,因此异常已被处理.
你throw不在任何try处理程序内,因此它会abort被调用.
这是你的代码与缩进清理了一些和内联的一些注释:
#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) {
// Catches and rethrows exception. Not inside a try thus leads to abort.
throw;
}
catch (...) {
// Will handle the case where the string is rethrown instead. No abort.
cout << "all handled here!"<< endl;
}
}
catch (...) {
std::cout<< "never printed" << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5440 次 |
| 最近记录: |