In which cases do Options 1 and 2 give different results/behaviour? Are they equivalent in all respects?
I tried with a non-existing in_out/sample2.txt
to force an exception and they behave the same.
int main() {
string fnamein2 = "in_out/sample2.txt";
ifstream ifstr;
try {
cout << "Reading " << fnamein2 << endl;
ifstr.open(fnamein2);
ifstr.exceptions( ifstream::eofbit | ifstream::failbit | ifstream::badbit );
} catch(const exception &e) { // <-- Option 1
//} catch(const ifstream::failure &e) { // <-- Option 2
cout << "There was an error: " << e.what() << endl;
}
return 0;
}
There is no difference in your scenario.
std::ifstream::failure
is specialized version of std::exception
(contains more details) but in your case you do not used them.
std::ifstream::failure
has code
method which gives you more information about an error. But if you do not need it, you can use base class.