C# language annoyance of the day

This actually applies to all the C-derived languages.

 

If I have code like this:


File f = File.OpenText(“MyFile.txt”);

f.ReadLine();

And I want to handle the case where the file is not found:



try

{

  File f = File.OpenText(“MyFile.txt”);

} catch (FileNotFoundException ex)

{

  Console.WriteLine(“File not found.”);

  return false;

}

 

f.ReadLine();

The problem with this is that the scope of f ends at the end of the try block.  To get around this, I’d have to declare f outside the try/catch:

 


File f;

try

{

  f = File.OpenText(“MyFile.txt”);

} catch (FileNotFoundException ex)

{

  Console.WriteLine(“File not found.”);

  return false;

}

 

f.ReadLine();


This seems less than elegant to me.  What I’d like to see is either variables living beyond the scope of a try/catch, or a way to mark a variable declared inside a block as being visible in the parent block.  For example:



try

{

  File parent.f = File.OpenText(“MyFile.txt”);

} catch (FileNotFoundException ex)

{

  Console.WriteLine(“File not found.”);

  return false;

}

 

f.ReadLine();

The syntax doesn’t matter that much as long as it’s clear; it’s the convenience of not having to go and separately declare and initialize all the variables you’re using inside the try/catch that would be useful.

 

Why not just do the f.ReadLine inside the try/catch?  Because if this is a large function (imagine the f.ReadLine is actually 80 lines of code), the distance between where the error is detected and where the error is handled can be quite large and you lose the ability to see ‘at a glance’ if the error is handled, and how.