Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is IDisposeable Called if Un-Handled Exception is Encountered in a Using Statement?

If I have the following, will IDisposeable still be called on DisposeableObject, or will the object remain opened because an un-handled exception is encountered?

using ( DisposeableObject = new Object() )
{
   throw new Exception("test");
}
like image 944
Judas Avatar asked Nov 24 '10 20:11

Judas


People also ask

What does IDisposable mean?

IDisposable is an interface that contains a single method, Dispose(), for releasing unmanaged resources, like files, streams, database connections and so on.

What does it mean when an object implements IDisposable?

Typically, types that use unmanaged resources implement the IDisposable or IAsyncDisposable interface to allow the unmanaged resources to be reclaimed. When you finish using an object that implements IDisposable, you call the object's Dispose or DisposeAsync implementation to explicitly perform cleanup.

Does Dispose get called after exception?

Dispose() does not get called in the attached code. Further more the exception that is thrown is not handled and the program blows up. You must be looking at the wrong file. "Dispose()" gets written to your temp file.

When should you use IDisposable?

If you access unmanaged resources (e.g. files, database connections etc.) in a class, you should implement IDisposable and overwrite the Dispose method to allow you to control when the memory is freed.


1 Answers

A using is like wrapping your code in a try...finally and disposing in the finally, so yes, it should be called.

like image 72
Mike Dour Avatar answered Nov 07 '22 21:11

Mike Dour