×

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

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Thread Program in Java

Thread Program in Java Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading,...

8 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.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

3 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

Java ResultSetMetaData

The data about another data is called Metadata. The ResultSetMetaData is used to store the data about ResultSet. The ResultSet Contains the columns, rows, names of table, datatypes etc. these...

2 minutes read.

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.