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");
}
And thing.Dispose
will be called as you leave the block, as the exception's thrown. If you want to combine a try/catch/finally and a using, you can either nest them:
try
{
...
using ( MyThing thing = new MyThing() )
{
...
}
...
}
catch ( Exception e )
{
....
}
finally
{
....
}
(Or put the try/catch/finally in the using):
using ( MyThing thing = new MyThing() )
{
...
try
{
...
}
catch ( Exception e )
{
....
}
finally
{
....
}
...
} // thing.Dispose is called now
Or you can unroll the using
and explicitly call Dispose
in the finally
block as @Quarrelsome demonstrated, adding any extra exception-handling or -recovery code that you need in the finally
(or in the catch
).
EDIT: In response to @Toran Billups, if you need to process exceptions aside from ensuring that your Dispose
method is called, you'll either have to use a using
and try/catch/finally
or unroll the using
- I don't thinks there's any other way to accomplish what you want.