GETah
GETah

Reputation: 21419

Exception throw from a using block

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?

Upvotes: 4

Views: 698

Answers (4)

Matthew Whited
Matthew Whited

Reputation: 22443

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();
}

Upvotes: 3

dknaack
dknaack

Reputation: 60486

The StreamReader will get disposed. Your code is good.

Upvotes: 2

Henk Holterman
Henk Holterman

Reputation: 273264

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.

Upvotes: 3

Mark Brackett
Mark Brackett

Reputation: 85655

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...
}

Upvotes: 11

Related Questions