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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Mamta MRank #268 · 9.4K reputationPosted Feb 21, 2012, 7:40 PM EST
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.
Jignesh TrivediRank #16 · 50.3K reputationPosted Feb 22, 2012, 1:41 AM EST
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.
SenthilkumarRank #387 · 6.5K reputationPosted Feb 29, 2012, 6:57 PM EST
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.
Sam HobbsRank #107 · 20.5K reputationPosted Feb 29, 2012, 11:48 PM EST
Hermes Condez37 reputationPosted Mar 1, 2012, 12:08 AM EST
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