×

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has always been run. Even the Prior execution or printing statements of the program is given we cannot know whether an exception happens or not to implement necessary statements are not.

The try-catch block is executed after the finally block is implemented or executed.

Finally Block Flow Chart

Java Finally Keyword

In the same manner that Java's final is a reserved keyword, finally is also a reserved keyword that cannot be used as an identifier. Finally, keyword ensures that a part of code will be run even if an exception is thrown when used in combination with a try/catch block. The control of the program to its source before the try and catch blocks are executed then last block will be executed.

Note: The JVM will implement or execute the finally block before terminating or stopping the application (if any), if we doesn’t handle the exception.

Usage of the Finally Block in Java

In Java programming language, "cleanup" code, such as terminating a file or a connection, can be inserted in the finally block. As part of programming specifications, we interface with databases by creating connections, using input and output streams, and resources inside a try block. It is advisable to use the finally block together with try-catch blocks as a good programmer to ensure the safety of resources and to make sure that there is no resource leak as part of our software.

The finally block is where you can print the essential statements.

Usage of Java keyword Finally

Let's understand and examine the various scenarios in which the Java finally block can be applied and implemented.

Case 1: In the absence of an exception

Let's look at the example below, where the Java programme doesn't raise any exceptions and the finally, block is executed following the try block.

TestFinallyBlock.java


class Fnl_Block {    
  public static void main (String s []) {
try {
// any exception is not thrown in the above code
   int ja=25/5;
   System.out.println(ja);
  }    
//executed without regard to exception happened or not
catch (NullPointerException e) {
System.out.println(e);
}    
 finally {  
System.out.println("Ececution of the finally block is always done.");
}    


System.out.println("remaining of the code...");
  }    
}    

Output:

Java finally block

Case 2: A catch block is not used when an exception occurs.

In this case, the catch block is unable to handle the exception when the code throws exception statements. Excepting this, the programme terminates improperly or irregularly after the finally block is executed after the running of try block.

public class Fnl_block_1{    
      public static void main (String s []) {
      try {    
        System.out.println("inner of try block");


        //The code below raises the divide-by-zero exception.
       int ja=25/0;
       System.out.println(ja);
      }    
//cannot handle exception of the arithmetic type
//can only accept exceptions of the Null Pointer type.
catch (Null_Pointer_Exptne) {
        System.out.println(e);
      }   
//checking whether an exception has occurred is executed or not.
      finally {  
        System.out.println("Execution of the finally block is always done");
      }    


      System.out.println("remaining of the code...");
      }    
    }    

Output:

Java finally block

Case 3: When a catch block is used to handle an exception that arises.

Example:

Let's look at the example below, where the catch block handles an exception that the Java code throws. After the block of try-catch, the finally block is then run. Additionally, the remaining code runs normally as well.

public class Fnl_Block_2{    
      public static void main (String s []){
      try {    
        System.out.println("Inner side of try block");


        //below code throws divide by zero exception  
       int ja=25/0;
       System.out.println(ja);
}  //handles the Arithmetic Exception 
            // Divide by zero


catch (Arithmetic_Exception e) {
        System.out.println("Exception handled");
        System.out.println(e);
      }   


      //regardless of whether an exception has occurred, /executes
      finally {  
        System.out.println("Execution of the final block is always done");
      }    


      System.out.println("remaining of the codeexecuted...");
      }    
    }  

Output:

Java finally block

Rule: There may be zero or more catch blocks for each attempt block, but there may only be one finally block.

Note: If the application terminates (either by calling System.exit() or by introducing a fatal error that causes the procedure to return), there they won't be carried out bt finally keyword.


Related Topics

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

JAR File in Java

What is a JAR File? JAR stands for Java Archive. It is a file format mainly used to combine many Java class files and the corresponding metadata and resources into one...

4 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

How to add double quotes in a string in Java

Strings are indicated using double-quotes. Double quotes are not printed; the values inside the double quotes are printed. There are different methods for adding double quotes to the string, such...

2 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Factorial of a Large Number in Java

We've already talked about a number's factorial. We must still go over the factorial of a large number separately, though. The method used to determine the factorial of a small...

8 minutes read.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.