我有以下代码:
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_argument
。 catch(...)
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/