Hi friends,
I want to know that If I return out of a try/finally in C# then, does the code in the finally-clause run? Please give an explanation in brief?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Hermes CondezPosted Mar 1, 2012, 5:08 AM
try
{
int myInt = (int) new object(); // This should cause an Exception
return; // code will NOT be pass
}catch
{
throw new Exception("My Error"); // code WILL BE PASS
return; // code will NOT be pass
}finally
{
GC.Collect(); // code WILL BE PASS
return; // code WILL BE PASS
}return; // code will NOT be pass
Sam HobbsPosted Mar 1, 2012, 4:48 AM
SenthilkumarPosted Feb 29, 2012, 11:57 PM
It will always run when control encountered in try block. The finally block mostly used to clean the resources like files.
The finally block can be used without exception(catch) block also.
Jignesh TrivediPosted Feb 22, 2012, 6:41 AM
Finnaly block is always called after try block.
if any code in try block is execute then its always finally block run or execute.
hope this help.
Mamta MPosted Feb 22, 2012, 12:40 AM
finally
{
// code block
return;
}
in the above case the code block is executed
but in the below case, it will not be executed because it is placed AFTER the return:
finally
{
return;
// code block
}
Hope this is clear.