question about using try/finally

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?
 
H

Hans Kesting

.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
 
M

Mateusz Pobudejski

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
 
F

Fabio

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'
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top