fstream打开文件时未处理异常

9

背景

我有这段简单的代码:

#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”,但我的捕获语句确实正确。我的问题是:我漏掉了什么?

5
确认 - πάντα ῥεῖ
5
使用 g++ 5.4.0 按预期工作。 - user2249683
3
在 Clang 3.8.0 上失败了。明显是一个 bug。 - WhiZTiM
3
但是如果你手动抛出一个异常,它会变成NSt8ios_base7failureB5cxx11E。也许在代码库中有两个定义,一个是C++03的,一个是C++11的,而03版本在open中隐藏了11版本? - jaggedSpire
4
是的,ios_base::failure 在 C++11 中经历了 ABI 更改。libstdc++ 在尝试管理这个转换过程中出现了一些混乱。https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66145 - T.C.
显示剩余6条评论
1个回答

0
为什么不使用file.good()file.fail()来处理异常呢?对于你尝试做的事情,它们可以完美地工作。

3
这应该是一条评论,因为它不是回答问题的内容。 - Jonathan Wakely

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接