Importance of the finally block in Java

There is one more block that is just like the try...catch block: is the finally block. The finally block will be executed irrespective of whether an exception is thrown. This block is executed if the program runs successfully, and even executed if the program doesn't run.

We'll explain this using the example we used in the The try...catch mechanism to handle exceptions section. We just add a finally block after the catch blocks and we give a print statement in it saying, delete cookies. The code block will look like this:

finally{    System.out.println("delete cookie")}

When we run the code, we get the following output:

I caught the Arithmeticerror/exceptiondelete cookie

One important point is that finally ...

Get Hands-On Automation Testing with Java for Beginners now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.