在fstream open上不处理异常

Bia*_*sta 9 c++ exception-handling c++11 system-error

上下文

我有这个简单的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

刚刚完成,这是编译命令:

 g++ -std=c++11 -g //  ...
Run Code Online (Sandbox Code Playgroud)

编译器的版本是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)
Run Code Online (Sandbox Code Playgroud)

正如你所读到的那样,投掷课是一个std::ios_base::failure,但我的抓住是正确的.

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

mat*_*405 0

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

  • 这应该是一条评论,因为它不是问题的答案。 (3认同)