c++ - 无法在 `catch(const std::exception &ex)` 中捕获 std::invalid_argument

标签 c++ exception try-catch

我有以下代码:

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 &ex) block 中捕获 std::invalid_argumentcatch(...) block 被触发。但据我所知,std::invalid_argument 继承自 std::exception 并且应该可以被第一个 block 捕获。是吗?我觉得我错过了一些明显的东西。

最佳答案

你应该按值抛出(没有 new):

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

关于c++ - 无法在 `catch(const std::exception &ex)` 中捕获 std::invalid_argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50572180/

相关文章:

c++ - 在 C++ 中组织命令的最佳方式

c++ - LLRP 与 QT 集成给出错误 "Skipping incompatible/path/libltkcpp.a when searching for -lltkcpp"

Java - 不可变局部变量

java - 自定义异常中的 super 调用

java - 尝试不要在 while(true) 循环中执行多次

c++ - 在 python 或 c++ 中获取全局 tcl 数组

c++ - 添加图像到 QQuickView

c++ - 捕获从其参数抛出的函数中的异常

php - 返回值、抛出异常和回滚事务

c# - 最后 try catch : Do something if no exception is thrown