Exception Handling in C# - A Second Attempt
(Page 4 of 8 )
To solve this problem you have to move the declarations of reader and source outside the try block. A second attempt might be:
private
static char[] ReadSource(string filename)
{
TextReader reader;
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
{
reader.Close();
}
return source;
}
This version has moved the declaration of reader and source out of the try block and consequently assigns to reader and source rather than initializing them. That's another difference (and two extra lines) from the "ideal" version of ReadSource. Nevertheless, you might consider it a reasonable solution if it worked. But it doesn't. The problem is that assignment is not the same as initialization and the compiler knows it. If an exception is thrown before reader is assigned then the call to reader.Close() in the finally block will be on reader which won't be assigned. C#, like Java, doesn't allow that.
Initializing the Reader
Clearly you have to initialize reader. A third 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
{
reader.Close();
}
return source;
}
This version introduces null which isn't in the "ideal" version of ReadSource. Nevertheless, you might still consider it a reasonable solution if it worked. But it doesn't (although it does compile). The problem is the call to reader.Close() could easily throw a NullReferenceException.
Next: Fourth Time's >>
More C# Articles
More By Jon Jagger