首页 > 解决方案 > C++ 异常处理:异常与 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;
}

标签: c++exceptionfstream

解决方案


您的情况没有区别。 std::ifstream::failurestd::exception(包含更多详细信息)的专用版本,但在您的情况下,您没有使用它们。

std::ifstream::failurecode方法可以为您提供有关错误的更多信息。但是如果你不需要它,你可以使用基类。


推荐阅读