C++ 异常处理:异常与 ifstream::failure

C++ Exception handling: exception vs. ifstream::failure

在哪些情况下选项 1 和 2 会给出不同的 results/behaviour? 它们在所有方面都等同吗?

我尝试使用一个不存在的 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::failurecode 方法,可以为您提供有关错误的更多信息。但如果你不需要它,你可以使用 base class.