Exception not caught in try catch block

前端 未结 5 858
太阳男子
太阳男子 2021-01-13 13:20

I do a simple throw \"TEST THROW\" and it isn\'t caught in my catch (std::exception& e). Is it because I\'m catching an std::exception& e?

相关标签:
5条回答
  • 2021-01-13 13:28

    This also may happen when you throw an exception of a an inherted type but the inhertence is private

    0 讨论(0)
  • 2021-01-13 13:31

    You can add a catch (...) block to get it.

    0 讨论(0)
  • 2021-01-13 13:49

    Since this is not a MCVE (what is Core?), I can't address explicitly the problem, but you are surely missing to

    #include <exception>
    

    Actually, GCC compiles even without the inclusion, but exception won't be caught and you will end up with

    terminate called after throwing an instance of 'std::exception'

    what(): std::exception

    ./{program}: {PID} Aborted (core dumped)

    0 讨论(0)
  • 2021-01-13 13:51

    You're throwing a const char*. std::exception only catches std::exception and all derived classes of it. So in order to catch your throw, you should throw std::runtime_error("TEST THROW") instead. Or std::logic_error("TEST THROW"); whatever fits better. The derived classes of std::exception are listed here.

    0 讨论(0)
  • 2021-01-13 13:53

    Another reason people may hit this issue, especially if they've been writing Java recently, is that they may be throwing a pointer to the exception.

    /* WARNING WARNING THIS CODE IS WRONG DO NOT COPY */
    try {
        throw new std::runtime_error("catch me");
    } catch (std::runtime_error &err) {
        std::cerr << "exception caught and ignored: " << err.what() << std::end;
    }
    /* WARNING WARNING THIS CODE IS WRONG DO NOT COPY */
    

    will not catch the std::runtime_error* you threw. It'll probably die with a call to std::terminate for the uncaught exception.

    Don't allocate the exception with new, just throw the constructor by-value, e.g.

    try {
        /* note: no 'new' here */
        throw std::runtime_error("catch me");
    } catch (std::runtime_error &err) {
        std::cerr << "exception caught and ignored: " << err.what() << std::end;
    }
    
    0 讨论(0)
提交回复
热议问题