简体   繁体   中英

Why is my C++ exception not being caught?

My code throws std::runtime_error , but doesn't catch it in the catch block. Instead it just calls std::terminate or, if I declared an exception-specifier on a function, calls std::unexpected .

The code simplifies down to:

void myfunc()
{
   throw new std::runtime_error("always throw");
}

int main()
{
    try {
        myfunc();
    } catch (std::runtime_error &err) {
        std::cerr << "intentionally ignored exception: " << err.what() << std::endl;
        return 0;
    }
    std::cerr << "unreachable?" << std::endl;
    return 1;
}

Similarly, if I add a throw specifier on my function, I crash out with std::unknown .

void myfunc() throw (std::runtime_error)
{
   throw new std::runtime_error("always throw");
}

You slipped in a Java-ism:

throw new std::runtime_error("always throw")
      ^^^

This causes the catch clause not to match, because it matches by type and you throw std::runtime_error* , ie a pointer to a std::runtime_error . It's expecting a plain std::runtime_error by-reference .

You could (untested) catch your original exception with

catch (std::runtime_error * exc) /* don't do this */

but you shouldn't do that.

Instead skip the new ; throw your exception directly and write:

void myfunc()
{
   throw std::runtime_error("always throw");
}

C++ is smart enough that if you catch the exception by-reference it won't get copied around.

Also, as @KonradRudolph points out in the comments, you should catch by const-reference:

catch (const std::runtime_error &err)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM