finally

finally creates a block of code that will be executed after a try/catch block has completed.

The finally block will execute even if no catch statement matches the exception.

finally block can be useful for closing file handles and freeing up any other resources. The finally clause is optional.


public class Main {
  // Through an exception out of the method.
  static void methodC() {
    try {
      System.out.println("inside methodC");
      throw new RuntimeException("demo");
    } finally {
      System.out.println("methodC finally");
    }
  }

  // Return from within a try block.
  static void methodB() {
    try {
      System.out.println("inside methodB");
      return;
    } finally {
      System.out.println("methodB finally");
    }
  }

  // Execute a try block normally.
  static void methodA() {
    try {
      System.out.println("inside methodA");
    } finally {
      System.out.println("methodA finally");
    }
  }

  public static void main(String args[]) {
    try {
      methodC();
    } catch (Exception e) {
      System.out.println("Exception caught");
    }
    methodB();
    methodA();
  }
}
Home 
  Java Book 
    Language Basics  

Exception Handler:
  1. Exception Handling
  2. Exception Types
  3. try and catch
  4. Displaying a Description of an Exception
  5. Multiple catch Clauses
  6. Nested try Statements
  7. Creates and throws an exception
  8. Methods with throws clause
  9. finally
  10. Java's Built-in Exceptions
  11. Creating Your Own Exception Subclasses
  12. Chained Exceptions