Java Tutorial Java Advanced Java References

Java finally Keyword



When Java interpreter executes a program and encounters an error or exception, it usually stops and throws error message. To handle such situation, Java has three keywords:

  • try: It is used to test a block of statements for error.
  • catch: It has a block of statements which executes when error occurs and handles error.
  • finally: It has a block of statements which executes regardless of try-catch blocks result.

try-catch blocks

In the example below, z is undefined, which raises an error. As the error occurred in try block of statement, it will be handled by its catch block of statement. Without try block, the program will stop immediately after an error and throw error message.

Syntax

try{
  statements;
}
catch (Exception e){
  statements;
}

Example:

public class MyClass {
  public static void main(String[] args) {
    try{
      int x = 10, y = 0, z;
      z = x/y;
      System.out.println(z);
    }
    catch (Exception e){
      System.out.println("An error occurred.");
    }
  }
}

The output of the above code will be:

An error occurred.

finally block

In the example below, finally block of statement is executed regardless of try-catch block results, which facilitates the program to close the file before proceeding further.

Syntax

try{
  statements;
}
catch (Exception e){
  statements;
}
finally{
  statements;
}

Example:

In the example below, finally block of code is used which is executed after try-catch blocks of code.

public class MyClass {
  public static void main(String[] args) {
    try{
      int x = 10, y = 0, z;
      z = x/y;
      System.out.println(z);
    }
    catch (NumberFormatException e){
      System.out.println("Number Format error.");
    }
    catch (ArithmeticException e){
      System.out.println("Arithmetic operation error.");
    }   
    catch (Exception e){
      System.out.println("An error occurred.");
    }
    finally{
      System.out.println("try-catch block finished.");
    }
  }
}

The output of the above code will be:

Arithmetic operation error.
try-catch block finished.

❮ Java Keywords