finally keyword in java

In Java, the finally keyword is used in conjunction with a try-catch block to define a block of code that will be executed whether an exception is thrown or not. The finally block ensures that certain cleanup or finalization tasks are performed, making it a useful construct for resource management.

Syntax:

try {
    // Code that may throw an exception
} catch (ExceptionType1 e1) {
    // Code to handle ExceptionType1
} catch (ExceptionType2 e2) {
    // Code to handle ExceptionType2
} finally {
    // Code in the finally block is always executed
    // regardless of whether an exception occurred or not
}

Use Cases:

  1. Resource Cleanup:
  • The finally block is commonly used to release resources such as closing files, database connections, or network sockets. This ensures that resources are released even if an exception occurs.
FileInputStream fileInputStream = null;
try {
    fileInputStream = new FileInputStream("example.txt");
    // Code to read from the file
} catch (FileNotFoundException e) {
    // Handle file not found exception
} finally {
    // Close the file input stream, regardless of whether an exception occurred or not
    if (fileInputStream != null) {
        try {
            fileInputStream.close();
        } catch (IOException e) {
            // Handle IOException during close
        }
    }
}
  1. Cleanup and Finalization:
  • Any code that needs to be executed for cleanup purposes, irrespective of whether an exception is thrown or not, can be placed in the finally block.
public void performOperation() {
    try {
        // Code that may throw an exception
    } catch (Exception e) {
        // Handle the exception
    } finally {
        // Code for cleanup or finalization
    }
}

Execution Flow with finally:

  1. If an exception occurs in the try block, control is transferred to the appropriate catch block.
  2. If no exception occurs in the try block, the catch block is skipped.
  3. The finally block is executed regardless of whether an exception occurred or not.
  4. After executing the finally block, control is transferred to the next statement after the try-catch-finally block.

Key Considerations:

  1. Uncaught Exceptions:
  • If an exception occurs and is not caught by any of the catch blocks, the finally block is still executed before the exception is propagated up the call stack.
try {
    // Code that may throw an exception
} finally {
    // This block will be executed even if an uncaught exception occurs
}
  1. return Statements:
  • If a return statement is encountered within the try or catch blocks, the finally block is executed before the method returns.
public int exampleMethod() {
    try {
        return 42;
    } finally {
        System.out.println("Finally block executed");
    }
}

finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception. Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns. This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning. The finally clause is optional. However, each try statement requires at least one catch or a finally clause

Demonstrate finally

class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {

System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}

Output

inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally

Leave a Comment