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;
}