Reputation: 21419
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
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
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
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