Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try catch block in C sharp

Tags:

c#

asp.net

I am using try catch and finally blocks in my project. my doubt here is... in why we needs to use finally block, actually if not use finally block then also the codes will execute after catch block. so we can do codes(to do resource free) after catch block. this will execute even if exception has occured. So is there any advantage if we use finally block?

like image 501
SaravanaManikandan Avatar asked Jul 01 '11 06:07

SaravanaManikandan


2 Answers

According to the answer of this previous SO Post:

The code inside a finally block will get executed regardless of whether or not there is an exception. This comes in very handy when it comes to certain housekeeping functions you need to always run like closing connections.

like image 139
npinti Avatar answered Oct 14 '22 02:10

npinti


Code will execute in a catch block only if an exception is thrown.

Code will execute in a finally block if an exception is thrown, and when no exception is thrown. Since you can rely on the finally block to always execute regardless of whether an exception was thrown or not, finally blocks are where you should clean up any resources you allocated, particularly non-managed resources such as file or OS handles.

You mention relying on execution of code after a catch block to release resources. This is not a safe assumption, since a) a properly constrained catch block does not catch all exceptions, but just the exceptions that the code needs to deal with and b) the catch block itself can throw or rethrow an exception. The code following the catch block might not be executed.

If you are in the habit of writing unqualified catch blocks that capture all exceptions and kill them, you're abusing exceptions.

like image 29
dthorpe Avatar answered Oct 14 '22 00:10

dthorpe