当你想捕获using代码段内的异常时,你打算怎么做呢?是在using里面写try-catch,还是把using写在try里面呢?
class Program
{
static void Main(string[] args)
{
//方法1
//using (var context = new TestClass())
//{
// try
// {
// throw new Exception("eee");
// }
// catch (Exception e)
// {
// Console.WriteLine(e);
// //throw e;
// }
//}
//方法2
try
{
using (var context = new TestClass())
{
throw new Exception("eee");
}
}
catch (Exception e)
{
Console.WriteLine(e);
//throw e;
}
Console.ReadLine();
}
}
public class TestClass : System.IDisposable
{
//供程序员显式调用的Dispose方法
public void Dispose()
{
Console.WriteLine("Run Dispose");
//调用带参数的Dispose方法,释放托管和非托管资源
Dispose(true);
//手动调用了Dispose释放资源,那么析构函数就是不必要的了,这里阻止GC调用析构函数
System.GC.SuppressFinalize(this);
}
//protected的Dispose方法,保证不会被外部调用。
//传入bool值disposing以确定是否释放托管资源
protected void Dispose(bool disposing)
{
Console.WriteLine("Run Dispose(" + disposing + ")");
if (disposing)
{
///TODO:在这里加入清理"托管资源"的代码,应该是xxx.Dispose();
}
///TODO:在这里加入清理"非托管资源"的代码
}
//供GC调用的析构函数
~TestClass()
{
Console.WriteLine("Run ~TestClass");
Dispose(false);//释放非托管资源
}
}
通过以上测试:
- 如果我们能正确处理异常,这两种写法都能捕获异常。
- 结论:没多大差别,要看业务逻辑。