Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are streams disposed of automatically in a try/catch statement?

Tags:

c#

.net

try-catch

If I create a stream inside of the try block and an exception is raised does the stream automatically get disposed of? For example:

try
{
   Stream stream = response.GetResponseStream();
   //Error Occurs
   stream.Close();
}
catch
{
   //Handle Error
}

If this is not the way to do it can you please suggest an approach?

like image 754
Edward Avatar asked Nov 28 '22 03:11

Edward


2 Answers

No, you need to use finally

Stream stream;
try
{
   stream = response.GetResponseStream();
   //Error Occurs
}
catch
{
   //Handle Error
}
finally
{
    if(stream != null)
        stream.Close();
}

Or, wrap your Stream declaration/definition in a using statement, which calls Close() automatically:

try
{
    using(Stream stream = response.GetResponseStream())
    {
        //Error happens
    }
    //stream.Dispose(), which calls stream.Close(), is called by compiler here
}
catch
{
   //Handle Error
}

Note that my two examples are not exactly equivalent - in the first, the exception is handled before steam.Close() is called, in the second the exception is handled after.

like image 179
BlueRaja - Danny Pflughoeft Avatar answered Dec 04 '22 13:12

BlueRaja - Danny Pflughoeft


The stream will not automatically close in this case.

If you wanted to ensure it closes in this context you'll want to use finally to ensure closure.

Alternatively I'd wrap the whole stream in a using.

using(Steam stream = response.GetResponseStream())
{
 // Do your work here
}
like image 33
Jamie Dixon Avatar answered Dec 04 '22 12:12

Jamie Dixon