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?
No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
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.
After executing the catch block, the control will be transferred to finally block(if present) and then the rest program will be executed.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With