๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

finally Block in Java Exception Handling  


Introduction

  • Definition:
    • In Java, the finally block is a block of code that is always executed after the execution of a try block, regardless of whether an exception occurs or not.
    • Even if an exception is not caught by the catch block, the finally block will still execute.
  • Use:
    • Release resources safely - Close files, database connections, or network streams to avoid resource leaks.
    • Perform cleanup tasks - Execute important tasks that must run, like resetting variables or clearing temporary data.
    • Maintain program reliability - Helps in writing robust and error-resistant programs.
    • Guarantee execution - Acts as a safety mechanism to make sure critical code is not skipped.
  • Syntax:
    • try
      {
          // risky code that may throw exception
      } 
      catch (ExceptionClassType e)
      {
          // exception handling code
      } 
      finally
      {
          // cleanup code (always executes)
      }
  • Example 1: Normal Execution
    • public class FinallyDemo1
      {
          public static void main(String[] args)
          {
              try
              {
                  System.out.println("Inside try block");
                  int data = 10 / 2; // no exception
                  System.out.println("Result: " + data);
              } 
              catch (ArithmeticException e)
              {
                  System.out.println("Exception caught: " + e);
              } 
              finally
              {
                  System.out.println("Finally block always executes");
              }
      
              System.out.println("Rest of the code...");
          }
      }
  • Example 2: Exception Occurs
    • public class FinallyDemo2
      {
          public static void main(String[] args)
          {
              try
              {
                  System.out.println("Inside try block");
                  int data = 10 / 0; // ArithmeticException
                  System.out.println("Result: " + data);
              } 
              catch (ArithmeticException e)
              {
                  System.out.println("Exception caught: " + e);
              } 
              finally
              {
                  System.out.println("Finally block always executes");
              }
      
              System.out.println("Rest of the code...");
          }
      }

Points to remember for finally block:
  1. finally block executes whether exception occurs or not.
    • It executes even if we use return statement inside the try or catch block.
    • public class FinallyDemo3
      {
          public static void main(String[] args)
          {
              System.out.println(m1());
          }
      
          static String m1()
          {
              try
              {
                  System.out.println("Inside try");
                  return "Returning from try";
              } 
              catch (Exception e)
              {
                  return "Returning from catch";
              } 
              finally
              {
                  System.out.println("Finally block executed before return");
              }
          }
      }
  2. The only cases where finally block may not execute
    • If the JVM exits using System.exit(0) before reaching finally.
    • If the program crashes due to a fatal error.