C++/finally 不管是否异常 finally 代码总被执行

发布时间 2023-12-04 13:24:52作者: 经纬视界
#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ifstream infile;
    try {
        infile.open("file.txt");
        if (!infile) {
            throw runtime_error("文件打开失败");
        }
        // 读取文件
    }
    catch (const exception& ex) {
        cerr << "出现异常: " << ex.what() << endl;
    }
    finally {
        infile.close();
    }
    return 0;
}