11

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

2 回答 2

13

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

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

于 2012-01-23T16:49:32.130 回答
7

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;
    }
}
于 2012-01-23T16:48:48.313 回答