打开包含不存在文件的文件流后没有异常抛出?
No exception throw after open a file stream with non-exist files?
我正在尝试使用
std::ifstream inStream;
inStream.open(file_name);
如果file_name
不存在,则不抛出异常。我怎样才能确保在这种情况下抛出?我正在使用 C++11
您可以通过在调用 open()
之前设置流 exception mask 来实现
std::ifstream inStream;
inStream.exceptions(std::ifstream::failbit);
try {
inStream.open(file_name);
}
catch (const std::exception& e) {
std::ostringstream msg;
msg << "Opening file '" << file_name
<< "' failed, it either doesn't exist or is not accessible.";
throw std::runtime_error(msg.str());
}
默认情况下 none 的流失败条件会导致异常。
我正在尝试使用
std::ifstream inStream;
inStream.open(file_name);
如果file_name
不存在,则不抛出异常。我怎样才能确保在这种情况下抛出?我正在使用 C++11
您可以通过在调用 open()
std::ifstream inStream;
inStream.exceptions(std::ifstream::failbit);
try {
inStream.open(file_name);
}
catch (const std::exception& e) {
std::ostringstream msg;
msg << "Opening file '" << file_name
<< "' failed, it either doesn't exist or is not accessible.";
throw std::runtime_error(msg.str());
}
默认情况下 none 的流失败条件会导致异常。