c++ - fstream 打开时不处理异常

标签 c++ c++11 exception-handling 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;
}

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

 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)

如您所见,throwing 类是一个 std::ios_base::failure,但我的捕获是正确的那个类。

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

最佳答案

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

关于c++ - fstream 打开时不处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39216129/

相关文章:

c++ - 传递 unique_ptr<T> 的 C++ vector 而不传递所有权

c++ - 调试 C++ 程序时出现奇怪的 gdb 消息

c++ - C++11如何优雅的检测模板类型是否派生自特定的基类?

php - 如何捕获函数 "include"PHP 的错误?

c# - 我不应该捕获哪些异常?

用于 getter 的 C++ 临界区

c++ - 由于使用 unsigned int,可变参数模板 c++ 上 Unresolved external symbol 错误

java - 与 Android 中的 e.printStackTrace() 混淆

c++ - 基于CMake编译C++项目时"fatal error: ' chrono ' file not found"

隐式声明的 C++ 编译器错误定义