【问题标题】:Exception is not handled on fstream open [duplicate]fstream 打开时未处理异常[重复]
【发布时间】:2016-08-29 22:28:07
【问题描述】:

上下文

我有这个简单的代码:

#include <iostream>
#include <fstream>
#include <system_error>

int main(int argc, char *argv[]) {
  std::ifstream file;
  file.exceptions(std::ios::failbit | std::ios::badbit);

  try {
    file.open("a_file_does_not_exist.txt", std::ios::in);
    file.close();
  } catch(const std::ios_base::failure& err) {
    std::cerr << err.code() << std::endl;
    return -1;
  }

  return 0;
}

只是为了完成,这是编译命令:

 g++ -std=c++11 -g //  ...

编译器版本为g++ (GCC) 6.1.1

平台:arch-linux 4.7.2-1.


问题

你可以想象,文件不存在,所以file.open(...)方法会抛出异常。问题是当我运行代码时未处理异常,并调用了std::terminate

奇怪的是输出:

terminate called after throwing an instance of 'std::ios_base::failure'
  what():  basic_ios::clear
Annullato (core dump creato)

如您所见,投掷类是 std::ios_base::failure,但我的发现是正确的。

我的问题是:我错过了什么?

【问题讨论】:

标签: c++ c++11 exception-handling system-error


【解决方案1】:

为什么不直接使用file.good()file.fail() 进行异常处理。它非常适合您尝试做的事情。

【讨论】:

  • 这应该是评论,因为它不是问题的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 2018-10-16
  • 2014-06-24
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多