Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Finally block



The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.

Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.

Syntax: Finally Block

A finally block appears at the end of the catch blocks and has the following syntax −

try {
   // Protected code
} catch (ExceptionType1 e1) {
   // Catch block
} catch (ExceptionType2 e2) {
   // Catch block
} catch (ExceptionType3 e3) {
   // Catch block
}finally {
   // The finally block always executes.
}

Points To Remember While Using Finally Block

  • A catch clause cannot exist without a try statement.

  • It is not compulsory to have finally clauses whenever a try/catch block is present.

  • The try block cannot be present without either catch clause or finally clause.

  • Any code cannot be present in between the try, catch, finally blocks.

  • finally block is not executed in case exit() method is called before finally block or a fatal error occurs in program execution.

  • finally block is executed even method returns a value before finally block.

Why Finally Block is to be Used?

  • finally block can be used for clean-up (closing) the connections, files opened, streams, etc. those must be closed before exiting the program.

  • It can also be used to print some final information.

Example - Usage of finally Block

Here is code segment showing how to use finally after try/catch statements after handling exception. In this example, we're creating an error accessing an element of an array using invalid index. The catch block is handling the exception and printing the same. Now in finally block, we're printing a statement signifying that finally block is getting executed.

Example.groovy

class Example {
   static void main(String[] args) {
      int[] a = new int[2];
      try {
         println("Access element three :" + a[3]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown  :" + e);
      }finally {
         a[0] = 6;
         println("First element value: " + a[0]);
         println("The finally statement is executed");
      }
   }
}

Output

This will produce the following result−

Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2
First element value: 6
The finally statement is executed

Example - Usage of finally block in case exception is not raised

Here is code segment showing how to use finally after try/catch statements even exception is not handled. In this example, we're creating an error accessing an element of an array using invalid index. As the catch block is not handling the exception, we can check in output that finally block is printing a statement signifying that finally block is getting executed.

Example.groovy

class Example {
   static void main(String[] args) {
      int[] a = new int[2];
      try {
         println("Access element three :" + a[3]);
      } catch (ArithmeticException e) {
         System.out.println("Exception thrown  :" + e);
      }finally {
         a[0] = 6;
         println("First element value: " + a[0]);
         println("The finally statement is executed");
      }
   }
}

Output

This will produce the following result−

First element value: 6
The finally statement is executed
Caught: java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2
	at Example.main(main.groovy:5)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
	at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)

Example - Using finally within a method with try-catch block

Here is code segment showing how to use finally block where a method can return a value within try block. In this example, we're returning a value within try block. We can check in output that finally block is printing a statement signifying that finally block is getting executed even after method returned a value to caller function.

Example.groovy

class Example {
   static void main(String[] args) {     
      println(testFinallyBlock());
   }

   static int testFinallyBlock() {
      int[] a = new int[2];
      try {
         return 1; 
      } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Exception thrown  :" + e);
      }finally {
         a[0] = 6;
         println("First element value: " + a[0]);
         println("The finally statement is executed");
      }
      return 0;
   }
}

Output

This will produce the following result−

First element value: 6
The finally statement is executed
1
Advertisements