簡體   English   中英

C ++異常處理:異常與ifstream :: failure

[英]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::failurestd::exception專用版本(包含更多詳細信息),但是在您的情況下,您不使用它們。

std::ifstream::failure具有code方法,可為您提供有關錯誤的更多信息。 但是,如果不需要它,則可以使用基類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM