question about using try/finally

  • Thread starter Thread starter Jeff
  • Start date Start date
J

Jeff

..NET 2.0

Lets say I have this code:

public int test ()
{
string s = "hello world"
try
{
int i = 4;
return i;
}
finally { s = 'newbie' }
}

Will the finally block be executed each time or will the return statment in
the try block leave the method without executing the finally block??

It is no problem in this example above. But lets say I set a write-lock on a
table in a database and then hope the finally block will remove that lock,
despite I call a return in the try block

any suggestions?
 
.NET 2.0
Lets say I have this code:

public int test ()
{
string s = "hello world"
try
{
int i = 4;
return i;
}
finally { s = 'newbie' }
}
Will the finally block be executed each time or will the return
statment in the try block leave the method without executing the
finally block??

It is no problem in this example above. But lets say I set a
write-lock on a table in a database and then hope the finally block
will remove that lock, despite I call a return in the try block

any suggestions?

quote (from http://msdn2.microsoft.com/en-us/library/zwc8s4fz(vs.71).aspx)

The finally block is useful for cleaning up any resources allocated in the
try block. Control is always passed to the finally block regardless of how
the try block exits.


So the finally *will* execute.

Hans Kesting
 
Jeff pisze:
.NET 2.0

Lets say I have this code:

public int test ()
{
string s = "hello world"
try
{
int i = 4;
return i;
}
finally { s = 'newbie' }
}

Will the finally block be executed each time or will the return statment in
the try block leave the method without executing the finally block??


finally block is always executed. The easiest way to find out is to
write a piece of code and look what happens...


Mateusz Pobudejski
 
Jeff said:
.NET 2.0

Lets say I have this code:

public int test ()
{
string s = "hello world"
try
{
int i = 4;
return i;
}
finally { s = 'newbie' }
}

Will the finally block be executed each time or will the return statment
in the try block leave the method without executing the finally block??

It is no problem in this example above. But lets say I set a write-lock on
a table in a database and then hope the finally block will remove that
lock, despite I call a return in the try block

any suggestions?

Try this step-by-step in debug:

public int test ()
{
string s = "hello world";
try
{
int i = 4;
int d = 0;
return i / d;
}
catch (Exception ex)
{
throw ex;
}
finally
{
s = 'newbie'
}
}
 
Back
Top