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/exception
delete cookie

One important point is that finally can work with or without the catch block; all it needs is to be written below a try block.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.175.243