Finally Block in Java

Let’s learn about the Finally Block in Java. Finally, a keyword is related to Exception Handling in Java.

In java finally block must be followed by the try or catch block and it always executes immediately after try-catch block exits.

 

The code inside the finally clause will always be executed, even if an exception is thrown from within the try or catch block. If your code has a return statement inside the try or catch block, the code inside the finally-block will get executed before returning from the method.

The main usage of finally block is to do clean up job. Keeping cleanup code in a finally block is always a good practice, even when no exceptions have occurred.

 

Finally Block in Java with Example

Let’s see the example of finally block. We will how finally block execute wether exception occurs or not.

Output:

Inside 1st catch Block
Inside 1st finally block
Inside 2nd finally block

 

Selenium Testing Video Tutorial:

 

Have you noticed, both finally blocks was executed even exception occurs or not?

Now let’s see the important points about the finally block.

  • You can use finally directly with try block like try-finally. finally, will execute after the try block.
  • After all other try-catch processing is complete, the code inside the finally block executes. It is not mandatory to include a finally block at all.
  • An exception is thrown in the try block and there’s no matching catch block in the method that can catch the exception. In this scenario, the call to the method ends, and the exception object is thrown to the enclosing method – as in the method in which the try-catch-finally blocks reside. But, before the method ends, the finally block is executed.
  • Will finally run after return ? – Before the try block runs to completion it returns to wherever the method was invoked. But, before it returns to the invoking method, the code in the finally block is still executed. So, remember that the code in the finally block will still be executed even if there is a return statement somewhere in the try block.
  • The finally block will not be called after return in a couple of unique scenarios: if System.exit() is called first, or if the JVM crashes.
  • For each try block there can be zero or more catch blocks, but only one finally block.

 

0 Comment

Leave a Reply