[英]C++ Exception handling: exception vs. ifstream::failure
在哪種情況下,選項1和2會給出不同的結果/行為? 它們在各個方面都等效嗎?
我嘗試使用不存在的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;
}
您的方案沒有任何區別。 std::ifstream::failure
是std::exception
專用版本(包含更多詳細信息),但是在您的情況下,您不使用它們。
std::ifstream::failure
具有code
方法,可為您提供有關錯誤的更多信息。 但是,如果不需要它,則可以使用基類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.