问题描述
我故意使用此方法将其写入文件,因此我尝试处理将其写入封闭文件的可能性:
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 ;
}
};
但是显然std :: exception不是关闭文件错误的适当例外,因为我故意在已关闭的文件上尝试使用此方法,但未生成我的"exception !!"注释.
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.
那我应该写什么例外?
推荐答案
默认情况下,流不会引发异常,但是您可以通过函数调用file.exceptions(~goodbit)
告诉它们引发异常.
Streams don't throw exceptions by default, but you can tell them to throw exceptions with the function call 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
相比:
for(;;) {
try {
std::cin >> input;
std::cout << input << '\n';
} catch(...) {
break;
}
}
实时观看: http://ideone.com/uWgfwj
这篇关于流异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!