异常处理和打开文件? [英] Exception Handling and Opening a File?

查看:80
本文介绍了异常处理和打开文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用文件打开例外来代替 .is_open()

Is it possible to use exceptions with file opening as an alternative to using .is_open()?

例如:

ifstream input;

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

如果是这样,什么类型是 someException

If so, what type is someException?

推荐答案

< a href = http://en.cppreference.com/w/cpp/io/basic_ios/exceptions rel = noreferrer> http://en.cppreference.com/w/cpp/io/basic_ios/exceptions

也请阅读此答案 11085151 引用了此文章

Also read this answer 11085151 which references this 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;
}

灯箱

编辑:通过const引用 2145147

catch exceptions by const reference 2145147

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

removed failbit from the exception set. Added URLs to better answers.

这篇关于异常处理和打开文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆