我故意使用这种写入文件的方法,所以我尝试处理写入关闭文件的可能性的异常:
void printMe(ofstream& file)
{
try
{
file << "\t"+m_Type+"\t"+m_Id";"+"\n";
}
catch (std::exception &e)
{
cout << "exception !! " << endl ;
}
};
但显然 std::exception 不是关闭文件错误的适当异常,因为我故意尝试在已经关闭的文件上使用此方法,但没有生成我的“异常!!”注释。
那么我应该写什么例外?
默认情况下,流不会引发异常,但您可以通过函数调用告诉它们引发异常file.exceptions(~goodbit)
.
相反,检测错误的正常方法只是检查流的状态:
if (!file)
cout << "error!! " << endl ;
原因是,在许多常见情况下,无效读取只是一个小问题,而不是一个主要问题:
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 http://ideone.com/uWgfwj
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)