流异常处理

Joy*_*Joy 8 c++ exception-handling exception ofstream

故意我有这个写入文件的方法,所以我试图处理我写入封闭文件的可能性的异常:

void printMe(ofstream& file)
{
        try
        {
            file << "\t"+m_Type+"\t"+m_Id";"+"\n";
        }
        catch (std::exception &e)
        {
            cout << "exception !! " << endl ;
        }
};
Run Code Online (Sandbox Code Playgroud)

但显然std :: exception不是关闭文件错误的合适例外,因为我故意尝试在已经关闭的文件上使用此方法,但我的"异常!!"注释未生成.

那么我应该写什么例外?

Moo*_*uck 14

Streams默认情况下不会抛出异常,但您可以告诉它们使用函数调用抛出异常file.exceptions(~goodbit).

相反,检测错误的常规方法只是检查流的状态:

if (!file)
    cout << "error!! " << endl ;
Run Code Online (Sandbox Code Playgroud)

这样做的原因是,有许多常见情况,无效读取是次要问题,而不是主要问题:

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
Run Code Online (Sandbox Code Playgroud)

相比:

for(;;) {
    try {
        std::cin >> input;
        std::cout << input << '\n';
    } catch(...) {
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

现场观看:http://ideone.com/uWgfwj


Alo*_*ave 5

ios_base::failure类型的异常,但是请注意,您应该使用ios::exceptions设置适当的标志以生成异常,否则只会设置内部状态标志来指示错误,这是流的默认行为。