Reputation: 8336
think about this:
StreamReader reader = null;
try
{
reader = new StreamReader(_fileName);
}
catch
{
//show error that file not found
reader.Dispose();
return false;
}
try
{
//code to read file
}
catch
{
//show error badly formed file
}
finally
{
reader.Dispose();
}
//return
the code above does not work when file can't be opened because it calls Dispose for null which results in exception.
i don't want to use using because i want to separate problems with opening the file and reading it. This could be achieved with million different catches but i don't want to go that way. Plus if using is same as try-finally would "hidden Dispose" throw an unwanted exception anyway? which would be the best way when all i need is to catch an exception opening it and an exception reading it?
Thanks & BR - Matti
Upvotes: 0
Views: 1129
Reputation: 31
The StreamReader
can throw the following exceptions so you could just handle these accordingly:-
ArgumentException ArgumentNullException FileNotFoundException DirectoryNotFoundException NotSupportedException ArgumentOutOfRangeException
Upvotes: 1
Reputation: 499132
It is better to use the using
statement:
using(StreamReader reader = new StreamReader(_fileName))
{
}
The compiler will create the correct dispose semantics for you.
And you can still use try
with this, not worrying about disposing it yourself:
try
{
using(StreamReader reader = new StreamReader(_fileName))
{
try
{
//code to read the file
}
catch
{
//show error badly formed file
}
}
}
catch
{
// show error that file not found
}
Upvotes: 6
Reputation: 13673
You should check whether the reader is null before you dispose it. Like so:
StreamReader reader = null;
try
{
//code to read file
}
catch
{
//show error badly formed file
}
finally
{
if( null != reader )
{
reader.Dispose();
}
}
Upvotes: 2
Reputation: 6627
Your code is correct if you check reader
for null before calling any methods on it, whereever that reader is located.
Using statement is not mandatory but is desirable.
Upvotes: 2