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

#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;
}
posted @ 2023-12-04 13:21  经纬视界  阅读(6)  评论(0编辑  收藏  举报