C# "Using" Syntax

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.

評論

I am fairly certain that your "gotcha" is not accurate. Since the StreamReader class implements IDisposable, the using statement will take care of the disposal of the object. Because the using statement acts like a finally block, it doesn't matter if you have an exception or return. Sep 29, 2008 at 17:12

 

回答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.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章