[英]C++ Exception handling: exception vs. ifstream::failure
In which cases do Options 1 and 2 give different results/behaviour? 在哪种情况下,选项1和2会给出不同的结果/行为? 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. 我尝试使用不存在的
in_out/sample2.txt
强制执行异常,并且它们的行为相同。
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
是std::exception
专用版本(包含更多详细信息),但是在您的情况下,您不使用它们。
std::ifstream::failure
has code
method which gives you more information about an error. std::ifstream::failure
具有code
方法,可为您提供有关错误的更多信息。 But if you do not need it, you can use base class. 但是,如果不需要它,则可以使用基类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.