C++ 使用异常处理机制处理文件打开失败:std::runtime_error
使用异常处理机制来处理打开失败的情况,抛出一个 std::runtime_error 异常,异常信息为'Could not open file',代码如下:
json VirtualDeviceBuilder::ReadFile(const char *path)
{
CALL_DEBUG_ENTER;
CHKPV(path);
std::cout << "read actions from '" << path << "'" << std::endl;
std::ifstream stream(path);
if (!stream.is_open()) {
throw std::runtime_error("Could not open file");
}
nlohmann::json model { nlohmann::json::parse(stream, nullptr, false) };
return model;
}
该代码使用 std::runtime_error 异常类来表示文件打开失败的情况。在 if (!stream.is_open()) 语句中,如果文件打开失败,则抛出一个 std::runtime_error 异常,异常信息为 "Could not open file"。这样,在调用 ReadFile 函数的代码中,就可以捕获该异常并进行相应的处理。
原文地址: https://www.cveoy.top/t/topic/nGo0 著作权归作者所有。请勿转载和采集!