- C# language annoyance of the day<DIV>This actually applies to all the C-derived languages.</DIV>
<DIV> </DIV>
<DIV>If I have code like this:</DIV>
<BLOCKQUOTE dir=ltr style="MARGIN-RIGHT: 0px">
<DIV>File f = File.OpenText(“MyFile.txt”);</DIV>
<DIV>f.ReadLine();</DIV></BLOCKQUOTE>
<DIV>And I want to handle the case where the file is not found:</DIV>
<DIV>
<BLOCKQUOTE dir=ltr style="MARGIN-RIGHT: 0px">
<DIV>try</DIV>
<DIV>{ </DIV>
<DIV> File f = File.OpenText(“MyFile.txt”);</DIV>
<DIV>} catch (<A href="ms-help://MS.VSCC.2003/MS.MSDNQTR.2003APR.1033/cpref/html/frlrfsystemiofilenotfoundexceptionclasstopic.htm">FileNotFoundException</A> ex)</DIV>
<DIV>{</DIV>
<DIV> Console.WriteLine(“File not found.”);</DIV>
<DIV> return false;</DIV>
<DIV>}</DIV>
<DIV> </DIV>
<DIV>f.ReadLine();</DIV></BLOCKQUOTE></DIV>
<DIV>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:</DIV>
<DIV> </DIV>
<BLOCKQUOTE dir=ltr style="MARGIN-RIGHT: 0px">
<DIV>File f;</DIV>
<DIV>try</DIV>
<DIV>{ </DIV>
<DIV> f = File.OpenText(“MyFile.txt”);</DIV>
<DIV>} catch (<A href="ms-help://MS.VSCC.2003/MS.MSDNQTR.2003APR.1033/cpref/html/frlrfsystemiofilenotfoundexceptionclasstopic.htm">FileNotFoundException</A> ex)</DIV>
<DIV>{</DIV>
<DIV> Console.WriteLine(“File not found.”);</DIV>
<DIV> return false;</DIV>
<DIV>}</DIV>
<DIV> </DIV>
<DIV>f.ReadLine();</DIV></BLOCKQUOTE>
<DIV dir=ltr>
<DIV>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:</DIV>
<BLOCKQUOTE dir=ltr style="MARGIN-RIGHT: 0px">
<DIV>
<DIV>try</DIV>
<DIV>{ </DIV>
<DIV> File parent.f = File.OpenText(“MyFile.txt”);</DIV>
<DIV>} catch (<A href="ms-help://MS.VSCC.2003/MS.MSDNQTR.2003APR.1033/cpref/html/frlrfsystemiofilenotfoundexceptionclasstopic.htm">FileNotFoundException</A> ex)</DIV>
<DIV>{</DIV>
<DIV> Console.WriteLine(“File not found.”);</DIV>
<DIV> return false;</DIV>
<DIV>}</DIV>
<DIV> </DIV>
<DIV>f.ReadLine();</DIV></DIV></BLOCKQUOTE>
<DIV>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.</DIV>
<DIV> </DIV>
<DIV>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.</DIV>
<DIV> </DIV>
<DIV> </DIV></DIV>Thu, 01 Sep 2005 19:17:07 GMT