fstream打开时未处理异常

Exception is not handled on fstream open

本文关键字:未处理 异常 fstream      更新时间:2023-10-16

上下文

我有一个简单的代码:

#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,但我的捕获是正确的。

我的问题是:我缺少什么?

为什么不使用file.good()file.fail()进行异常处理呢。它将非常适合你正在尝试做的事情。