Exception Handling in C# - Fourth Time's
(Page 5 of 8 )
One way to solve this problem is to guard the call to reader.Close(). A fourth attempt therefore might be:
private
static char[] ReadSource(string filename)
{
TextReader reader = null;
char[] source;
try
{
FileInfo file = new FileInfo(filename);
int length = (int)file.Length;
source = new char[length];
reader = file.OpenText();
reader.Read(source, 0, length);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
return source;
}
Of course, the guard on reader.Close() isn't in the "ideal" version of ReadSource. But this is a reasonable version if only because it does, finally, work. It's quite different from the "ideal" version but with a bit of effort you can refactor it to this:
private
static char[] ReadSource(string filename)
{
FileInfo file = new FileInfo(filename);
int length = (int)file.Length;
char[] source = new char[length];
TextReader reader = file.OpenText();
try
{
reader.Read(source, 0, length);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
return source;
}
In some cases you might be able to drop the null guard inside the finally block (you can in the above case) but in general this is the best you can do with a finally block solution. (Consider if file.OpenText returned null, or if reader was assigned to inside the try block, or reader was passed as a ref/out argument inside the try block.) You have to add a try block, a finally block, and an if guard. And if you are using Java you have to do those three things every time. And therein is the biggest problem. If this solution was truly horrible and completely and utterly different to the ideal solution it wouldn't matter a jot if we could abstract it all away. But in Java you can't. The Java road stops here, but the C# road continues.
Next: Using Statements >>
More C# Articles
More By Jon Jagger