Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to have finally block without try and catch?

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?

like image 586
prashanth Avatar asked Jun 26 '13 08:06

prashanth


People also ask

Can finally block exist without try catch?

Yes, it is not mandatory to use catch block with finally. You can have to try and finally.

Is finally block mandatory with try catch in Java?

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.


2 Answers

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.

like image 177
AllTooSir Avatar answered Sep 21 '22 18:09

AllTooSir


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 } 
like image 22
Duncan Jones Avatar answered Sep 22 '22 18:09

Duncan Jones