Java finally statement

In this chapter you will learn:

  1. How to use Java finally statement
  2. Syntax to use Java finally statement
  3. Note on Java finally statement
  4. Example - Java finally statement

Description

Any code that would be executed regardless after a try block is put in a finally block.

Syntax

This is the general form of an exception-handling block:


try { //  w  ww .j a v a 2s  .c  o  m
// block of code to monitor for errors 
} 
catch (ExceptionType1 exOb) { 
// exception handler for ExceptionType1 
}
catch (ExceptionType2 exOb) { 
// exception handler for ExceptionType2 
}
// ... 
finally { 
// block of code to be executed after try block ends 
}

Note

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.

Example


public class Main {
  // Through an exception out of the method.
  static void methodC() {
    try {//from   ww  w . j  a va  2s .  com
      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();
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What are Java's Built-in Exceptions
Home »
  Java Tutorial »
    Java Langauge »
      Java Exception Handling
Java Exception
Java Exception types
Java try catch statement
Java throw statement
Java throws statement
Java finally statement
Java Built-in Exceptions
Java custom exception class
Java chained exceptions