【问题标题】:Exception Handling and Opening a File?异常处理和打开文件?
【发布时间】:2012-03-29 01:10:27
【问题描述】:

是否可以使用打开文件的异常来替代使用.is_open()

例如:

ifstream input;

try{
  input.open("somefile.txt");
}catch(someException){
  //Catch exception here
}

如果是,someException 是什么类型?

【问题讨论】:

标签: c++ exception-handling inputstream file-handling


【解决方案1】:

来自the cppreference.com article on std::ios::exceptions

失败时,设置失败位标志(可以通过成员失败检查),并且根据设置的值设置异常,可能会引发异常。

【讨论】:

    【解决方案2】:

    http://en.cppreference.com/w/cpp/io/basic_ios/exceptions

    另请阅读此答案11085151,其中引用了此article

    // ios::exceptions
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    void do_something_with(char ch) {} // Process the character 
    
    int main () {
      ifstream file;
      file.exceptions ( ifstream::badbit ); // No need to check failbit
      try {
        file.open ("test.txt");
        char ch;
        while (file.get(ch)) do_something_with(ch);
        // for line-oriented input use file.getline(s)
      }
      catch (const ifstream::failure& e) {
        cout << "Exception opening/reading file";
      }
    
      file.close();
    
      return 0;
    }
    

    Wandbox上运行的示例代码

    编辑:通过 const 引用 2145147 捕获异常

    编辑:从异常集中删除了故障位。添加 URL 以获得更好的答案。

    【讨论】:

    • 我们需要使用 ifstream file 作为类型吗?我们可以使用 ofstream 吗?
    • 假设您正在写入文件,那么是的,您可以像使用 ofstream 一样管理异常。使用 ofstream::failbit、ofstream::badbit 和 ofstream::failure。
    • @KarlM:嗯,在这种情况下并没有错。虽然它多余的。
    • 顺便说一句,通过引用捕获异常
    • 我要指出你的代码没有像你想象的那样工作。当您遇到 EOF 时将引发异常,因为您将 ifstream::failbit 设置为异常掩码,至少在 Mac OS 10.10 Yesomite 上是这样。如果遇到EOF时读取文件,ios_base::failbit将与ios_base::eofbit一起设置。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多