【问题标题】:Unable to catch std::invalid_argument in `catch(const std::exception &ex)`无法在 `catch(const std::exception &ex)` 中捕获 std::invalid_argument
【发布时间】:2018-05-28 18:57:05
【问题描述】:

我有以下代码:

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.");
}

我无法在catch (const std::exception &amp;ex) 块中捕获std::invalid_argument。而是触发了 catch(...) 块。但据我所知,std::invalid_argument 继承自 std::exception 并且应该可以被第一个块捕获。是吗?我觉得我错过了一些明显的东西。

【问题讨论】:

  • 您缺少的主要是一个最小的、完整的示例,它可以编译、运行和演示问题。
  • 了解new 的作用。
  • const std::exception &amp;exstd::exception const* ex.

标签: c++ exception try-catch


【解决方案1】:

你应该按值抛出(不带new):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 2019-03-05
    • 1970-01-01
    • 2011-04-16
    • 2013-08-12
    相关资源
    最近更新 更多