Im trying to catch an exception thrown when an error ocurred reading a file in a class method from main. The simplified code is this:
#include <iostream>
#include <fstream>
#include <string>
class A
{
public:
A(const std::string filename)
{
std::ifstream file;
file.exceptions( std::ifstream::failbit | std::ifstream::badbit);
file.open(filename);
}
};
int main()
{
std::string filename("file.txt");
try
{
A MyClass(filename);
}
catch (std::ifstream::failure e)
{
std::cerr << "Error reading file" << std::endl;
}
}
I compile this code with:
$ g++ -std=c++11 main.cpp
If file.txt exists nothing happens, but when it doesn't, the program terminates with the following error:
terminate called after throwing an instance of 'std::ios_base::failure'
what(): basic_ios::clear
zsh: abort (core dumped) ./a.out
But I expected the code to catch the exception and show the error message. Why is it not catching the exception?