Quote:
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:
Code:
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:
Code:
{
int myValue = 10;
Console.WriteLine(myValue);
}
Woody Z
http://www.learntoprogramnow.com