C# "Using" Syntax
When you see a using statement, think of this code:
StreadReader rdr = null;
try
{
rdr = File.OpenText("file.txt");
//do stuff
}
finally
{
if (rdr != null)
rdr.Dispose();
}
So the real answer is that it doesn't do anything with the exception thrown in the body of the using block. It doesn't handle it or rethrow it.
using statements do not eat exceptions.
All "Using" does is scope your object to the using block, and automatically calls Dispose() on the object when it leaves the block.
There is a gotcha though, if a thread is forcefully aborted by an outside source, it is possible that Dispose will never be called.
using
allows the exception to boil through. It acts like a try/finally, where the finally disposes the used object. Thus, it is only appropriate/useful for objects that implement IDisposable
.
It throws the exception, so either your containing method needs to handle it, or pass it up the stack.
try
{
using (
StreamReader rdr = File.OpenText("file.txt"))
{ //do stuff
}
}
catch (FileNotFoundException Ex)
{
// The file didn't exist
}
catch (AccessViolationException Ex)
{
// You don't have the permission to open this
}
catch (Exception Ex)
{
// Something happened!
}