I don t really understand the question - you throw an exception as you normally would.
If MyThing
implements IDisposable
, then:
using ( MyThing thing = new MyThing() )
{
...
throw new ApplicationException("oops");
}
当您离开块时,会调用thing.Dispose
,因为抛出了异常。如果您想将try/catch/finaly和using组合在一起,您可以嵌套它们:
try
{
...
using ( MyThing thing = new MyThing() )
{
...
}
...
}
catch ( Exception e )
{
....
}
finally
{
....
}
(或者将try/catch/finally放在using中):
using ( MyThing thing = new MyThing() )
{
...
try
{
...
}
catch ( Exception e )
{
....
}
finally
{
....
}
...
} // thing.Dispose is called now
或者,您可以使用展开,并在finally
块中显式调用Dispose
,如@Quarrelsome所示,在finally
(或catch
)中添加所需的任何额外异常处理或恢复代码。
编辑:为了响应@Toran Billups,如果除了确保调用Dispose
方法外,还需要处理异常,则必须使用和try/catch/finaly
使用来使用-我认为没有任何其他方法可以实现您想要的。