Subject: Try/Catch/Finally
Posted By: rohit.sharma Post Date: 1/12/2007 4:42:23 PM
I have a query that is related to try/catch/finally. I m giving an example:
myfunction()
{
try
{
System.IO.StreamReader objReader = new System.IO.StreamReader("text.txt");
Console.WriteLine(objReader.ReadToEnd());
}
catch(System.IO.FileNotFoundException exc)
{
new Exception(exc.Message);
}
finally
{
objReader.Close();
}
}

Now this code would not compile as the objReader is declared within the try block and the variable that you declared in try block can't be accessed in finally block. Now my question is Why is it so? i want to know the internal implementation of try/catch/finally. Thanks in advance :)

Reply By: Imar Reply Date: 1/12/2007 6:11:59 PM
Just declare the StreamReader *outside* the try block and instantiate it *inside* the try block....

Imar
---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of ASP.NET 2.0 Instant Results and Beginning Dreamweaver MX / MX 2004
While typing this post, I was listening to: Butterflies & Hurricanes by Muse (Track 10 from the album: Absolution) What's This?
Reply By: woodyz Reply Date: 1/12/2007 10:44:06 PM
quote:
Originally posted by rohit.sharma

I have a query that is related to try/catch/finally. I m giving an example:
myfunction()
{
try
{
System.IO.StreamReader objReader = new System.IO.StreamReader("text.txt");
Console.WriteLine(objReader.ReadToEnd());
}
catch(System.IO.FileNotFoundException exc)
{
new Exception(exc.Message);
}
finally
{
objReader.Close();
}
}

Now this code would not compile as the objReader is declared within the try block and the variable that you declared in try block can't be accessed in finally block. Now my question is Why is it so? i want to know the internal implementation of try/catch/finally. Thanks in advance :)


This is a scope issue that is not specific to try/catch/finally.  When you declare a variable within a particular block, it is visible only within that block.  A block is defined with opening and closing braces. In the following case, intCounter only can be used in the "if block" it is declared in, and will only be created only if someCondition is true:
if (someCondition)
{
   int counter ;
   for (counter=1; counter<=100; counter++)
   // Do important things here
}

You can also declare blocks simply by enclosing code withing braces as you please.  There usually isn't a pressing reason to do this, but it can be useful occasionally:

{
   int myValue = 10;
   Console.WriteLine(myValue);
}


Woody Z
http://www.learntoprogramnow.com

Go to topic 54758

Return to index page 65
Return to index page 64
Return to index page 63
Return to index page 62
Return to index page 61
Return to index page 60
Return to index page 59
Return to index page 58
Return to index page 57
Return to index page 56