我正在尝试编写一个Dispose
方法,该方法具有抛出异常的潜力。
通过try-finally
声明以using
模式调用dispose:
using(var widget = new Widget())
{
widget.DoYourThing();
}
问题是如果Dispose
方法引发异常,它将替换using
块体内可能引发的任何异常。通常,这个例外比在体内抛出的例外更有用。
我想要的是编写Dispose
方法,以便在正在进行的异常时吞下自己的异常。像下面这样的东西是理想的:
protected virtual void Dispose(bool disposing)
{
try
{
this.Shutdown();
}
catch(Exception)
{
this.Abort();
// Rethrow the exception if there is not one already in progress.
if(!Runtime.IsHandlingException)
{
throw;
}
}
}
有什么能提供这些信息吗?
答案 0 :(得分:1)
您的Dispose
方法是否真的有必要抛出异常?
也许您应该创建另一个具有不同名称的处理方法,并在必要时抛出异常。然后通过调用另一个方法来实现Dispose
,该方法包含在try
块中,该块将吞下异常,以便Dispose
永远不会抛出。
答案 1 :(得分:0)