[英]ofstream exception handling
Deliberately I'm having this method which writes into a file, so I tried to handle the exception of the possiblity that I'm writing into a closed file:我故意使用这种写入文件的方法,因此我尝试处理写入关闭文件的可能性的异常:
void printMe(ofstream& file)
{
try
{
file << "\t"+m_Type+"\t"+m_Id";"+"\n";
}
catch (std::exception &e)
{
cout << "exception !! " << endl ;
}
};
But apparently std::exception is not the appropriate exception for a closed file error because I deliberately tried to use this method on an already closed file but my "exception !! " comment was not generated.但显然 std::exception 不是关闭文件错误的适当异常,因为我故意尝试在已经关闭的文件上使用此方法,但未生成我的“异常 !!”注释。
So what exception should I have written ??那么我应该写什么异常??
Streams don't throw exceptions by default, but you can tell them to throw exceptions with the function call file.exceptions(~goodbit)
.默认情况下,流不会抛出异常,但您可以通过函数调用
file.exceptions(~goodbit)
告诉它们抛出异常。
Instead, the normal way to detect errors is simply to check the stream's state:相反,检测错误的正常方法只是检查流的状态:
if (!file)
cout << "error!! " << endl ;
The reason for this is that there are many common situations where an invalid read is a minor issue, not a major one:这样做的原因是在许多常见情况下,无效读取是小问题,而不是大问题:
while(std::cin >> input) {
std::cout << input << '\n';
} //read until there's no more input, or an invalid input is found
// when the read fails, that's usually not an error, we simply continue
compared to:相比:
for(;;) {
try {
std::cin >> input;
std::cout << input << '\n';
} catch(...) {
break;
}
}
See it live: http://ideone.com/uWgfwj现场观看: http : //ideone.com/uWgfwj
ios_base::failure类型的异常,但是请注意,您应该使用ios::exceptions设置适当的标志以生成异常,否则只会设置内部状态标志来指示错误,这是流的默认行为。
consider following:考虑以下:
void printMe(ofstream& file)
{
file.exceptions(std::ofstream::badbit | std::ofstream::failbit);
try
{
file << "\t"+m_Type+"\t"+m_Id";"+"\n";
}
catch (std::ofstream::failure &e)
{
std::cerr << e.what() << std::endl;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.