Finally


How To Understand Java Finally Easily?

People who are not familiar with Java may feel a little confused when they how you can use Java finally in error handling. And, you can expect it to guarantee the execution of code. However, there may be certain situations where you can’t execute it.

What is The Actual Meaning Of Java Finally?

Basically, Java Finally can be defined as a block of code. You are allowed to use it along with the try keyword. Prior to completing the method, it interprets the code that runs after the try and any catch block.

In case you catch an exception, this block executes. Moreover, with both class method and variable, you can use this keyword. It is not possible to represent the final class by an instance, override a final method and a final variable that doesn’t have the ability to be reassigned. .

To run a cleanup-type statement, this block enables you to perform an action you prefer to execute regardless of how the protected code may proceed. Furthermore, before you destroy an object, and create it, you can use the finalize() method. .

How Is It Useful?

Commonly, Java finally is utilized to execute a clean-up code, such as to close connections, to close files, or free up threads. That is because it executes irrespective of an exception.

Significant Points

  • A finally block should have a link with a try block.
  • It is optional, but it is enough for exception handling. Nevertheless, you must place it to run after the execution of the try block.
  • If there is an exception, before the finally block, you can execute the catch block.
  • Usually, an exception is similar to any other exception.
  • The Java finally statements can execute when the try block has control transfer statements, for instance, return, break or continue.

Example :

Com.knowledge2life public class Main { public static void main(String args[]){ try{ int data=25/5; System.out.println(data); } catch(NullPointerException e){ System.out.println(e); } finally { System.out.println("Knowledge2life"); } System.out.println("Website"); } }

OUTPUT:

5
Knowledge2life
website