Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception throw from a using block

Tags:

c#

I have the following code:

try{
    using (StreamReader reader = new StreamReader(...), Encoding.ASCII)){
        // Code that can throw an exception
    }
}catch (Exception error){
    // Display error...
}

What will happen to the StreamReader in case there is an exception thrown from within the using block?

Should I add a finally clause where I close the stream?

like image 720
GETah Avatar asked Dec 02 '22 00:12

GETah


1 Answers

The StreamReader will be disposed automatically by the using, as it's essentially a nested try/finally:

try{
    StreamReader reader =  new StreamReader(...), Encoding.ASCII);
    try {
        // Code that can throw an exception     
    } finally {
        reader.Dispose();
    }
} catch (Exception error) {
    // Display error...
}
like image 126
Mark Brackett Avatar answered Dec 09 '22 10:12

Mark Brackett