lundi 29 août 2016

Exception is not handled on fstream open

Context

I have this simple code:

#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;
}

Just to complete, this is compile command:

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

The version of compiler is g++ (GCC) 6.1.1.

Platform: arch-linux 4.7.2-1.


The problem

As you can imagine, the file does not exists so the method file.open(...) will throw an exception. The problem is when I run the code an exception is not handled, and std::terminate is called.

The strange thing is the output:

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

As you can read, the throwing class is a std::ios_base::failure, but my catch is right that class.

My question is: what am I missing?

Aucun commentaire:

Enregistrer un commentaire