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
It is better to use the
usingstatement:The compiler will create the correct dispose semantics for you.
And you can still use
trywith this, not worrying about disposing it yourself: