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
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.
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.
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.
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.
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.
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