Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the try catch finally block work?

In C#, how does a try catch finally block work?

So if there is an exception, I know that it will jump to the catch block and then jump to the finally block.

But what if there is no error, the catch block wont get run, but does the finally block get run then?

like image 351
omega Avatar asked Nov 24 '12 20:11

omega


People also ask

Can we use try catch in finally block?

No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.

When finally block gets executed in try catch finally?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

How does try finally work java?

What Is finally? finally defines a block of code we use along with the try keyword. It defines code that's always run after the try and any catch block, before the method is completed. The finally block executes regardless of whether an exception is thrown or caught.

What happens after a try catch?

After executing the catch block, the control will be transferred to finally block(if present) and then the rest program will be executed.


2 Answers

Yes, the finally block gets run whether there is an exception or not.

 Try     [ tryStatements ]     [ Exit Try ] [ Catch [ exception [ As type ] ] [ When expression ]     [ catchStatements ]     [ Exit Try ] ] [ Catch ... ] [ Finally     [ finallyStatements ] ] --RUN ALWAYS End Try 

See: http://msdn.microsoft.com/en-us/library/fk6t46tz%28v=vs.80%29.aspx

like image 114
James Hill Avatar answered Oct 07 '22 00:10

James Hill


Yes the finally clause gets exeucuted if there is no exception. Taking an example

     try         {             int a = 10;             int b = 20;             int z = a + b;         }         catch (Exception e)         {             Console.WriteLine(e.Message);         }         finally         {             Console.WriteLine("Executed");         } 

So here if suppose an exception occurs also the finally gets executed.

like image 45
Sohail Avatar answered Oct 06 '22 23:10

Sohail