Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use the finally-block in Java's try-catch-finally

When should I use code snippet A instead of snippet B (i.e. what are the benefits of using snippet A)?:

Snippet A:

try {
    // codeblock A
}
catch (Exception ex) {
    // codeblock B
}
finally {
    //codeblock C
}

Snippet B:

try {
    // codeblock A
}
catch (Exception ex) {
    // codeblock B
}

//codeblock C
like image 663
poplitea Avatar asked Sep 13 '11 17:09

poplitea


People also ask

Should I use Finally in try catch?

The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error. Both catch and finally are optional, but you must use one of them.

When finally block executed in try catch finally?

catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed. The code in the finally block will always be executed before control flow exits the entire construct.

When we use finally block in Java?

The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not.

When to use try with finally?

Generally try-finally is used to assure that some piece of code gets executed irrespective if the exception occurs or not. Catch block is generally missing because code in try block does not throw any checked exception which can be caught.


1 Answers

Use a finally block if you have code that must execute regardless of whether or not an exception is thrown.

Cleaning up scarce resources like database connections are a good example.

like image 118
duffymo Avatar answered Oct 18 '22 15:10

duffymo