Unable to catch std::invalid_argument in `catch(const std::exception &ex)`

时间:2018-05-28 18:57:05

标签: c++ exception try-catch

I have the following code:

void App::start()
try
{
    initialize();
    //...

    m_errorCode = 0;
}
catch (const std::exception &ex)
{
    std::cerr << ex.what() << '\n';
    m_errorCode = -1;
}
catch (...)
{
    std::cerr << "Unknown exception\n";
    m_errorCode = -2;
}

void App::initialize()
{
    m_controller = createController();
    //...
}

std::unique_ptr<IController> App::createController() const
{
    if (m_config.m_controllerType == "iot_v1")
    {
        return std::make_unique<ControllerIotV1>();
    }

    if (m_config.m_controllerType == "iot_v2")
    {
        return std::make_unique<ControllerIotV2>();
    }

    throw new std::invalid_argument("Unsupported controller type.");
}

I am unable to catch std::invalid_argument in the catch (const std::exception &ex) block. The catch(...) block is being triggered instead. But as far as I know, std::invalid_argument inherits from std::exception and should be catchable by the first block. Is it? I feel like I am missing something obvious.

1 个答案:

答案 0 :(得分:2)

你应该按价值(不new)投掷:

throw std::invalid_argument("Unsupported controller type.");