我故意让这个方法写入文件,所以我尝试处理写入关闭文件的可能性的异常:
void printMe(ofstream& file)
{
try
{
file << "\t"+m_Type+"\t"+m_Id";"+"\n";
}
catch (std::exception &e)
{
cout << "exception !! " << endl ;
}
};但很明显,std::exception不是适合于关闭文件错误的异常,因为我故意尝试在已经关闭的文件上使用此方法,但我的“异常!!”未生成评论。
那么我应该写什么异常呢??
发布于 2012-04-27 00:58:16
默认情况下,流不会抛出异常,但您可以通过函数调用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
发布于 2012-04-27 00:58:39
类型的异常,但是请注意,您应该使用设置适当的标志来生成异常,否则将只设置内部状态标志来指示错误,这是流的默认行为。
发布于 2020-10-21 16:27:30
请考虑以下内容:
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;
}
};https://stackoverflow.com/questions/10337915
复制相似问题