Click here to Skip to main content
15,904,652 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello,

We use try catch finally block to handle exception.

try
{ }
catch
{ }
finally
{ }


is it always necessary to execute finally block.... if not then how please explain with short example


Thanks & Regards
Srishti Gupta
Posted
Updated 28-May-18 4:40am

1.The finally block should be used for executing code that is mandatory to be executed even there is no exception thrown, like disposing the used resources (disposable resources used in try block), in other cases the finally block is not mandatory.

2.You could see more details (including example source code) in my next article: MVC Basic Site: Step 2 - Exceptions Management[^]
 
Share this answer
 
v2
Try : Your code which you used to perform operations.

Catch : To handle exceptions(in very simple words 'Errors') that may occur while performing operations inside Try block.

Finally : Its guaranteed to be executed regardless of result of Try or Catch.

Finally is not mandatory block,but its useful in cases e.g. close database connections etc.

Regards..
 
Share this answer
 
Comments
srishti_ 20-Jun-14 2:09am    
i know this but i want to know how can we prevent to execute finally block this is my question
Member 14207397 2-Apr-19 2:16am    
System.Exit(0);
Hi Srishti Gupta, Please check this article: Using Try... Catch..., Finally![^]

Gives you a good insight of exception handling..

It is not mandatory to have a finally block always. But it is advisable. You can dispose all the objects which you don't need. Also it can be used when you need to write some code that needs to be executed irrespective of an exception occurs or not.

Hope it helps.

Regards
Dinesh Kumar.V.
 
Share this answer
 
v2
Comments
srishti_ 20-Jun-14 1:49am    
how can we prevent to execute finally block
Member 14207397 2-Apr-19 2:42am    
If you are using a Console Application -

Environment.Exit(0);
if you are using a Windows Forms based application

Application.Exit();

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