×

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection must be put inside the Java finally block. The Java finally block ensures that whatever statements are present in the finally block must be executed irrespective of the exception raised in the program or not. The Java finally can be used with the try-catch or can be used only with the try keyword.

Java finally syntax

The syntax of the finallykeyword is mentioned below.

 try
{
    // Statements that are potent to cause an exception
}
catch
{
   // for Handling the raised exception
}
finally
{
   // Statements that have to be executed irrespective of an exception raised or not
}
We can also use finally without using catch.
try
{
    // Statements that are potent to cause an exception
}
finally
{
   // Statements that have to be executed irrespective of an exception raised or not
} 

Java finally Keyword Example

Let’s try to understand the usage of the keyword finally with the help of some examples.

FileName: FinallyExample.java

 public class FinallyExample
{
// main method
public static void main(String argvs[])
{
try
{
// an int array of 9 elements
int arr[] = new int[9];
arr[10] = 90; // raises ArrayIndexOutOfBoundsException
System.out.println(arr);  // this statement never gets executed
} 
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("The used index is out of range." + e);
} 
finally
{
System.out.println("This print statement has to be executed.");
} 
System.out.println("Finally, out of the try - catch - finally block"); 
}  
} 

Output:

 The used index is out of range.java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 9
This print statement has to be executed.
Finally, out of the try - catch – finally block 

Explanation:The try-catch block handles the ArrayIndexOutOfBoundsException. After the try-catch block, the control shiftsto the finally block. Now observe the following example.

FileName: FinallyExample1.java

 public class FinallyExample1
{
// main method
public static void main(String argvs[])
{
try
{
int x = 7 / 0; // raises ArithmeticException
System.out.println(x);  // this statement never gets executed
} 
finally
{
System.out.println("This print statement has to be executed.");
} 
    // the last print statements
System.out.println("Finally, out of the try - finally block"); 
}  
} 

Output:

 This print statement has to be executed.
Exception in thread "main" java.lang.ArithmeticException: / by zero
               at FinallyExample1.main(FinallyExample1.java:9) 

Explanation:In this program, we see that the ArithmeticException is raised in the try block. Even though the raised exception is not handled by the program, the finally block executes. It shows the importance of the finally block.  Any sensitive piece of code that has to be executedhas to be put only in the finally block. Notice the last print statement is not executed. It is because the raised exception is not handled, and that leads to the abnormal termination of the program.

Non-Execution of the Finally Block

Even though finally block ensures that some statements have to be executed, no matter what happens. However, there are some scenarioswhere even the finally block does not execute. The following program illustrates the same.

FileName: FinallyExample2.java

 public class FinallyExample2
{
// main method
public static void main(String argvs[])
{
try
{
System.out.println("Inside the Java try block.");
System.exit(0); // nothing executes after the execution of this statement
}
catch (Exception e)
{
System.out.println("Inside the Java catch block" + e);
}
finally
{
System.out.println("Inside the Java finally block");
}
System.out.println("Finally, out of the try - catch - finally block");
}  
} 

Output:

Inside the Java try block.

Explanation: In this program, we observe thatfinally block is not executed. Because of the statement System.exit(0);.The System.exit(0); statement stops the program by forcefully terminating the JVM (Java Virtual Machine). Hence, the finally block does notexecute.

Remember:

1) The finally block cannot exist independently. It has to come either with a try block or with a try-catch block.

2) The finally block always executes after the try block.

3) Presence of a catch block does not guarantee that the finally block executes after the catch block or not. The following program illustrates the same.

FileName: FinallyExample3.java

Output:

 Inside the Java try block.
Inside the Java finally block.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
               at FinallyExample3.main(FinallyExample3.java:16) 

Explanation: In this program, we see the finally block is executed, and the catch block is not executed. The reason behind it is the type of exception raised in the program. The catch block is expecting the ArithmeticException to be raised in the try block. However, the try block raises the ArrayIndexOutOfBoundsException. Thus, there is a mismatch between what is expected and what is present. As the raised exception is not handled, the last print statemen also does not get executed, and the program terminates abnormally. In this example, we see that after the try block, the finally block gets executed, even though the catch block is present. Now, observe the following program.

FileName: FinallyExample4.java

 public class FinallyExample4
{
// main method
public static void main(String argvs[])
{
// try - catch - finally    
try
{
System.out.println("Inside the Java try block.");
   // creating an array of three elements
   int arr[] = new int[3];
arr[3] = 5; // raises ArrayIndexOutOfBoundsException
}
catch (ArrayIndexOutOfBoundsException ae)
{
System.out.println("Inside the Java catch block \n " + ae);
}
finally
{
System.out.println("Inside the Java finally block.");
}
// the last print statement
System.out.println("Finally, out of the try - catch - finally block.");
}  
} 

Output:

 Inside the Java try block.
Inside the Java catch block
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Inside the Java finally block.
Finally, out of the try - catch - finally block. 

Explanation: In this program, we see the finally block is executed after the catch block. It is because the raised exception is getting handled in the catch block.

4) The finally block does not guarantee that an exception cannot be raised in its block.

5) If the raised exception inside the finally block is not handled, the program terminates abnormally.

6) One can use try-catch inside the finally block to handle the raised exception inside the finally block. Observe the following program.

FileName: FinallyExample5.java

 public class FinallyExample5
{
// main method
public static void main(String argvs[])
{
// try - catch - finally    
try
{
System.out.println("Inside the Java try block.");
   String str = null;
str.equals("tutorial & example");
}
catch (NullPointerException ne)
{
System.out.println("Inside the Java catch block " + ne);
}
finally
{
System.out.println("Inside the Java finally block.");
   // try-catch block inside the finally block
   try
   {
       // raising the ArithmeticException
       // inside the finally block
       int x = 78 / 0;
   }
catch(ArithmeticException ae)
   {
System.out.println("Handling exception successfully in the catch block. " + ae);
   }
}
// the last print statement
System.out.println("Finally, out of the try - catch - finally block.");
}  
} 

Output:

 Inside the Java try block.
Inside the Java catch block java.lang.NullPointerException
Inside the Java finally block.
Handling exception successfully in the catch block. java.lang.ArithmeticException: / by zero
Finally, out of the try - catch - finally block. 

Explanation: The above program shows an exception can be raised as well as handled in the finally block.


Related Topics

Static() Function in Java

The static keyword in Java is suitable for variables, constants, and functions. The static keyword is mainly used to control storage so that it may be appropriately used. We shall...

3 minutes read.

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Difference between C, C++, java

C Language: C language is a procedure oriented language. It has been invented by Dennis Ritchie in the year 1970. It is one of the computer programming language. The purpose of...

3 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Resultset in java

Resultset: A result set is an interface that is present in the package java.sql and the resultset is used to store the data that are returned from the database table after...

5 minutes read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

SHA Decrypt in Java

In this section, we will be acknowledged about the decryption of SHA in Java. Java SHA The SHA cryptographic hash algorithm in cryptography outputs the hash value as an approximately 40-digit-long hexadecimal...

4 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.