question about scope of try variables

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all,
The variables declared inside try block cant be accessed inside its
corresponding finally block. When I used to explain finally concept to anyone
I would usually tell them (briefly) that the finally block is existing there
cuz of the logic inside try block, if try is not there finally wont be there.
If try and finally are so closely related than finally should share the scope
of try. Please explain the rational behind this scope restriction.

I wanted to do
try
{
string tmp = this.Text;
...
}
catch{}

finally
{

this.Text = tmp;
}

but since I cant access try scope variable in finally sshould I move the
settings outside them like:

string tmp = this.Text
try ..


finaly {}
this.Text = tmp;

Thanks & Regards,

Abubakar.
http://joehacker.blogspot.com
 
Abubakar said:
Hi all,
The variables declared inside try block cant be accessed inside its
corresponding finally block. When I used to explain finally concept to
anyone
I would usually tell them (briefly) that the finally block is existing
there
cuz of the logic inside try block, if try is not there finally wont be
there.
If try and finally are so closely related than finally should share the
scope
of try. Please explain the rational behind this scope restriction.

Finally has a specific purpose, that is the code within that block will be
executed if an exception occurs in the try block or not. In other words it
is almost always executed(it is possible that certain big failures could
cause finally blocks not to execute, but these are rare and generally result
in dead programs anyway.) Because the purpose of a finally block is to run
code whether or not the stuff inside the try block actually executed, it
doesn't make sense to be able to use the variables within the try block,
since the assignment might not have happened(code before the assignment may
have failed, the initalizer in the assignment might have failed, or a random
error could have occured between initalization(reading from this.Text) and
the actual assignment to tmp).

To do what you want:

string tmp = this.Text;
try
{

}
finally
{
this.Text = tmp;
}
 
Back
Top