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.