Java Finally Block

Use the finally block to specify a section of code that will run whether or not an exception is thrown inside a try block. It is frequently employed for maintenance tasks, resource management, or making sure certain actions are completed before leaving the code block. The finally block in Java is used to put important codes such as clean-up code, e.g. closing the file or closing the connection.

The finally block executes whether exceptions rise or not and whether exceptions are handled or not. Finally, it contains all the crucial statements regardless of whether the exception occurs or not.

Syntax for try-finally block:

try
{
  statement1;
  statement2;
}
finally
{
  statement3;
}
Syntax for try-catch-finally block:
try
{
  statement1;
  statement2;
}
catch(Exceptiontype e1)
{
   statement3;
} 
finally
{
  statement4;
}

Flow Chart:

flow chart

Some important rules for using a finally block or clause are:

  • A finally block is optional, but at least one of the catch or finally blocks must exist with a try.
  • It must be defined at the end of the last catch block. If the finally block is defined before a catch block, the program will not compile successfully.
  • Unlike catch, multiple finally blocks cannot be declared with a single try block. That is, there can be only one finally clause with a single try block.

Control flow of try-catch-finally block in Java

So far, you will have observed that when an exception occurs within try block in a program, the rest of the statements in try block are not executed, and the control of execution directly gets passed to the subsequent catch block.

However, there are certain statements in a program that need to be executed, whether the exception has occurred or not. For this, Java provides a keyword named “finally“.

The code within the finally block is always executed whether the exception is thrown by try block or not. If an exception is thrown with a matching catch block, the first catch block is executed, and then finally block is executed.

On the other hand, if no matching catch block is found with an exception object thrown by try block, finally block is executed by JVM after the execution of try block, and the program terminates.

The diagrammatic representation of the working of Java try-catch-finally block is shown in the below figure.

Control flow

Program:

1. With ‘try’ and ‘catch’ Blocks:

try {
}
catch (Exception e) {
}
finally {
}

Explanation:

Regardless of whether an exception is thrown or caught, the code included in the finally block runs after the code contained in the try block.

2. With Return Statement:

public static int divide (int a, int b) {
    try {
    	return a / b;
    } catch (ArithmeticException e) {
    	return -1;
    }
finally {
        System.out.println("Finally block executed");
    }
}

Output:

Finally block executed

Explanation:

The finally block’s logic runs before the actual return, even if the try block contains a return statement.

3. With Uncaught Exception:

try {
    int result = 10 / 0;
}
finally {
    System.out.println("Finally block executed");
}

Output:

Exception in thread “main” java. lang.ArithmeticException: / by zero
at YourClassName.main(YourClassName.java:line_number)
Finally block executed

Explanation:

The finally block still operates even when the program ends as a result of the uncaught exception.

4. Exception Handling and Finally Block:

public class FinallyExample1 {
    public static void main(String[] args) {
    	try {
        	int result = 10 / 0;
            System.out.println("Result: " + result);
    	}
  	catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e.getMessage() +" ");
    	}
  	finally {
            System.out.println("Finally block executed");
    	}
    }
}

Output:

Exception caught: / by zero
Finally block executed

Explanation:

  • The try block in this example tries to divide by zero, which leads to an ArithmeticException.
  • The catch block captures the exception and outputs a warning.No matter the exception, the finally block’s function is run, printing “Finally block executed.”

In Java finally block they are specifying some cases:

Here, these are some different cases where Java finally block can be used.

Case 1: When an exception does not occur

Let’s see the below example where the Java program does not throw any exception, and the finally block is executed after the try block.

Program:

class Main {	
  public static void main (String args []) {	
  try {	
   int data=25/5;	
   System.out.println(data);	
  }	
  catch (NullPointerException e) { 
System.out.println(e); 
}	
 finally { 
System.out.println("finally block is always executed"); 
}  	
System.out.println("rest of the code...");	
  }	
}

Output:

5

finally block is always executed
rest of the code…

Explanation:

  • Integer division is attempted in the try block with the formula: int data = 25 / 5; the variable data is given the value 5 as a result of the division’s success.
  • 5 is printed to the console via the System.out.println(data); command.
  • The catch block is bypassed since there is no catch block for the specific NullPointerException exception, and no exception of that type is thrown.
  • Finally, the block is carried out:
  • Message “finally block is always executed” is printed to the console.
  • Execution of the following statement: System.out.println(“rest of the code…”);
  • The console displays “rest of the code…”

Case 2: When an exception occurs but is not handled by the catch block

Here, the code throws an exception; however, the catch block cannot handle it. Despite this, the finally block is executed after the try block, and then the program terminates abnormally.

Program:

public class Main {	
  	public static void main(String args[]){  
  	try {	
      System.out.println("Inside the try block"); 	
   	int data=25/0;	
       System.out.println(data);	
  	}	
      catch(NullPointerException e){ 
        System.out.println(e); 
  	}  
        System.out.println("finally block is always executed"); 
  	}	
     System.out.println("rest of the code...");	
  	}	
    }

Output:

Inside the try block
finally block is always executed
Exception in thread “main” java.lang.ArithmeticException: / by zero
at Main.main(Main.java:9)

Explanation:

  • The main method starts to run.
  • It prints “Inside the try block” to the console.
  • With int data = 25 / 0, an attempt at integer division is made, but because it is forbidden to divide by zero, an ArithmeticException is produced.
  • Due to the lack of a catch block specifically for the ArithmeticException, the program proceeds to the next step.
  • As the finally block is completed, the message “Finally block is always executed” is written to the console.
  • The program cannot proceed because of the uncaught exception. The application will, therefore, close, and the specifics of the ArithmeticException will be displayed.

Case 3:When an exception occurs and is handled by the catch block

Where the Java code throws an exception, and the catch block handles the exception. Later, the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally.

Program:

public class Main {	
public static void main(String args[]){  
try {	
System.out.println("Inside try block"); 
int data=25/0;	
              System.out.println(data);	
      	}
          catch(ArithmeticException e){ 
            System.out.println("Exception handled"); 
            System.out.println(e); 
      	}  
          finally { 
            System.out.println("finally block is always executed"); 
      	}	
          System.out.println("rest of the code...");	
      	}
}

Output:

Inside try block
Exception handled
java.lang.ArithmeticException: / by zero
finally block is always executed
rest of the code…

Explanation:

  • A try block of code is attempted to be executed by the program.
  • The text “Inside try block” appears.
  • A failed attempt to divide 25 by 0 results in an ArithmeticException.
  • The ArithmeticException catch block is executed:
  • It prints “Exception handled”.
  • Java.lang.ArithmeticException: / by zero) is reported along with the specifics of the exception.
  • The ultimately block is always carried out:
  • It prints, “finally block is always executed”.
  • After printing “rest of the code…”, the program ends.Best in Class

Summary

The finally block in Java is a powerful tool used in exception handling and resource management scenarios. It provides a way to ensure that a specific piece of code is executed, regardless of whether an exception occurs or not within a try block.

The finally block has several important characteristics:

  • Always Executed: The code within the finally block is guaranteed to execute, regardless of whether an exception is thrown, caught, or even if no exception occurs at all.
  • Cleanup and Resource Release: It is commonly used to perform cleanup operations, release resources like file handles, database connections, or network sockets, and ensure that any allocated resources are properly deallocated.
  • Order of Execution: After the try block’s code completes (whether normally or due to an exception), the catch block (if applicable) is executed. Following that, the finally block’s code executes.
  • Exception Propagation: If an uncaught exception occurs within the try block, the finally block still executes before the exception propagates further up the call stack.
  • Usage with return Statements: The finally block is executed even if a return statement is present in the try or catch block. It’s useful for performing actions before returning from a method, such as cleanup tasks.
  • Try-Finally: In certain cases, you might use a try-finally combination without a catch block when you want to ensure specific cleanup, even if no exceptions need to be caught and handled.

Conclusion

Overall, the finally block enhances the reliability and robustness of Java programs by allowing developers to enforce critical actions and cleanups in a consistent manner, regardless of the control flow or exceptions that may occur.Bottom of Form.