I am trying to use the finally block without using the try/catch blocks but getting the error in Eclipse.
Can I use the finally block without using the try/catch blocks?
Yes, it is not mandatory to use catch block with finally. You can have to try and finally.
Therefore, we will put code like closing connections, stream objects, etc. or any cleanup code in the finally block so that they can be executed even if an exception occurs. The finally block in Java is usually put after a try or catch block. Note that the finally block cannot exist without a try block.
finally should have atleast a try block, catch is optional. The point of finally blocks is to make sure stuff gets cleaned up whether an exception is thrown or not. As per the JLS
A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.
Hence a finally should always be preceded by a try block.
You must have a try block with a finally block. The try block defines which lines of code will be followed by the finally code. If an exception is thrown prior to the try block, the finally code will not execute.
Adding catch blocks is optional:
try { // something } finally { // guaranteed to run if execution enters the try block }
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