【问题标题】:ofstream exception handlingofstream异常处理
【发布时间】:2012-04-26 16:53:48
【问题描述】:

我故意使用这种写入文件的方法,所以我尝试处理我正在写入已关闭文件的可能性的异常:

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

但显然 std::exception 不是关闭文件错误的适当异常,因为我故意尝试在已关闭的文件上使用此方法,但没有生成我的“异常!!”注释。

那么我应该写什么例外??

【问题讨论】:

    标签: c++ exception exception-handling ofstream


    【解决方案1】:

    默认情况下流不会抛出异常,但您可以通过函数调用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

    【讨论】:

    • 好吧,我只是想习惯异常处理,但很高兴知道“Streams 默认情况下不会抛出异常”,非常感谢
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      考虑以下:

      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;
              }
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多