Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use finally blocks? [duplicate]

Tags:

java

.net

finally

As far as I can tell, both of the following code snippets will serve the same purpose. Why have finally blocks at all?

Code A:

try { /* Some code */ } catch { /* Exception handling code */ } finally { /* Cleanup code */ } 

Code B:

try { /* Some code */ } catch { /* Exception handling code */ } // Cleanup code 
like image 379
Mohammad Nadeem Avatar asked Aug 06 '10 06:08

Mohammad Nadeem


People also ask

What is the key reason for using finally blocks?

But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return , continue , or break . Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Can we have 2 finally blocks?

In C#, multiple finally blocks in the same program are not allowed. The finally block does not contain any return, continue, break statements because it does not allow controls to leave the finally block.

When should we use finally?

In this meaning, finally most commonly occurs in the normal mid position for adverbs, between the subject and the main verb, after the modal verb or the first auxiliary verb, or after be as a main verb: There were no taxis and we finally got home at 2 pm.

Why do we use finally block Mcq?

Explanation: Sometimes there is a need to execute a set of code every time the program runs. Even if the exception occurs and even if it doesn't, there can be some code that must be executed at end of the program. That code is written in finally block. This block is always executed regardless of exceptions occurring.


1 Answers

  • What happens if an exception you're not handling gets thrown? (I hope you're not catching Throwable...)
  • What happens if you return from inside the try block?
  • What happens if the catch block throws an exception?

A finally block makes sure that however you exit that block (modulo a few ways of aborting the whole process explicitly), it will get executed. That's important for deterministic cleanup of resources.

like image 91
Jon Skeet Avatar answered Sep 21 '22 14:09

Jon Skeet