Site icon TechVidvan

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:

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

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.

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:

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:

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:

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:

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:

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.

Exit mobile version