c++ - 使用异常检查 C++ 流时出错

标签 c++ exception fstream

我有一个 X 类,它有一个可以抛出自定义异常的 writeBinary(ostream) 方法 如果流出现问题。

写入fstream和错误检查的正确方法是什么?

这是我的版本:我想知道我是否遗漏了什么或者我需要 catch 错误。

    ofstream ofs("X.binary.tmp");
    if (!ofs) {
       cerr << "Could not open file for writing";
       throw runtime_error("Could not open file for writing");
    }
    try {
      x.writeBinary(ofs);
     } catch(CustomException& e) {
      // remove the temporary file
       int x = unlink("X.binary.tmp");
       if (x) {
        cerr << "Failed to remove file";
       }
       throw;
     }

    if (!ofs) { // is this check necessary?
     int x = unlink("X.binary.tmp"):
    if (x) {
        cerr << "Failed to remove file";
       }
       throw std::runtime_error("Stream error");
    }
   rename("X.binary.tmp", "X.binary");

能否简化这种异常的大杂烩?

最佳答案

使事情变得不那么困惑的一种方法是创建一个资源处理对象 - 所以一个“tempfile”对象,它通过给构造函数的名称打开一个新文件,如果文件名不是,则在析构函数中调用 unlink '空白。然后让它有一个重命名功能,重命名文件并将名称设置为空白,例如。当然,还有一个函数可以为您提供对象的 ofstream。

我敢肯定它的代码一样多,但它看起来会干净得多,而且会让生活更轻松。

编写处理大量潜在错误的代码并不容易,您可能已经注意到...

关于c++ - 使用异常检查 C++ 流时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14071781/

相关文章:

模板类的 C++ 转换

objective-c - NSInvalidArgumentException 未被代码捕获

ruby-on-rails - AssociationType 与嵌套模型表单上的预期类型不匹配

c++ - 在读/写 fstream 上查找/写入某个位置时自动扩展文件大小

c++ - QT QTextEdit setText 崩溃

c++ - C 标准 : Character set and string encoding specification

c# - 进程因 StackOverFlowException C# 而终止

c++ - 为什么 'new line' 偏移 .txt 文件中的所有字符字节位置 +1?

c++ - fstream文件读取失败

c++ - gSOAP 到 WCF。应用程序/soap+xml;字符集=utf-8