C# "Using" Syntax
問題
Does the using catch the exception or throw it? i.e.
using (StreamReader rdr = File.OpenText("file.txt"))
{
//do stuff
}
If the streamreader throws an exception is it caught by using or thrown so the calling function can handle it?
回答1
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.
回答2
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.
評論
回答3
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
.