4

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?

0

4 Answers 4

11

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...
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

No, the inner using() {} (which is in essence a try/finally) takes care of the reader.

This code is basically OK.

Comments

3

The using block is the same as calling the .Dispose() method in a finally. And .Dispose() on StreamReader calls .Close().

using (var reader = new StreamReader(...)) {
    //do work
}

... is the same as ...

var reader = new StreamReader(...);
try {
    //do work
}
finally {
    reader.Dispose();
}

Comments

2

The StreamReader will get disposed. Your code is good.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.