繁体   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