#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
char *str = new char[10];
__try
{
int i = 0;
int j = 10 / 2;
}
__finally //不管有没发生异常, 总会运行下面复合语句
{
cout << "hehe" <<endl;
delete []str;
cout << "释放" <<endl;
}
return 0;
}
__try里面没发生异常, 有运行__finally
再看下面
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
char *str = new char[10];
__try
{
int i = 0;
int j = 10 / i; //除0错误
}
__finally //不管有没发生异常, 总会运行下面复合语句
{
cout << "hehe" <<endl;
delete []str;
cout << "释放" <<endl;
}
return 0;
}
__try里面发生异常, __finally同样被执行
本文探讨了C++中使用`__try`和`__finally`关键字进行异常处理及资源释放的过程,通过两个实例展示了即使在`__try`内未发生异常,`__finally`块仍会被执行,确保资源正确释放。

198

被折叠的 条评论
为什么被折叠?



