Click here to Skip to main content
15,904,926 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
WHY finally will execute even when there is a return in try block?

I know its by design, in finally block i should do resource cleanup - that's why the finally block is always executed no matter what the exception handling code is.

But "WHY" it will execute is my question? This was asked to my friend in an interview, so even i got confused after discussing with him, please clarify, thanks in advance.?
Posted
Updated 22-Aug-13 21:21pm
v3

Because if it didn't, resources would not get cleaned up.

That's the blunt answer and it's pretty much all you need. The thing is, whenever you exit a try...finally block, by whatever means, the code in the finally block is always executed. That means if you leave because you:

1) Got to the end of the try code - execute the finally block.
2) Execute a return statement - execute the finally block.
3) Throw an exception using throw - execute the finally block.
4) Cause an exception in a called method, even if it is 100 methods deep, by making a mistake and it isn't handled by a catch anywhere - execute the finally block.
5) Use catch to handle an exception: when you exit the catch block by any means - execute the finally block.

The whole idea is that you code will never continue past the try...finally without executing the code in the finally block and releasing the resources you allocated.
 
Share this answer
 
 
Share this answer
 
Finally block will execute anyway at any circumstance.Finally block is having very important role in real time scenario.
Suppose for example you have an open database connection during execution of certain code block.During execution an error raised,which interrupted your normal flow of execution.Now control will go inside Try block which in turn will throw respective error to catch block.Note here that error is handled,but your connection to database is still open.As database is open for certain user,no other user will be able to do transaction at that time.So you should open your connection as late as possible and should close connection as early as possible.To ensure closing of connection at any circumstance provide your database close connection command inside finally block to ensure closing of open connection.So finally block is very important.
 
Share this answer
 
Finally is not called after return
 
Share this answer
 
Comments
lukeer 23-Aug-13 6:49am    
That's plain wrong.
See MSDN[^] on the subject.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900