How to use the try, catch, and finally blocks in Java

Introduction

The try, catch, and finally blocks are important components of the Java programming language. They are used to handle errors and exceptions in Java. The three blocks are used in the following way:

  • The try block is used to specify a block of code that may throw an exception.
  • The catch block is used to handle the exception if it is thrown.
  • The finally block is used to execute the code after the try and catch blocks have been executed.

Syntax

The following code snippet shows how to use these blocks:

public class Main {
public static void main(String[] args) {
try {
// Code that may throw an exception
} catch (Exception e) {
// Code to handle the exception
} finally {
// Code that is always executed
}
}
}

Explanation

  • Lines 3–5: The try block contains the code that may throw an exception. If an exception is thrown in the try block, the code in the catch block is executed.
  • Lines 5–7: The catch block contains the code that handles the Exception. The order of the try, catch, and finally blocks is important. If we place the finally block before the catch block, the code will not compile.
  • Lines 7–8: The finally block contains the code that is always executed. The finally block is executed even when an exception is not thrown. This is useful for cleanup code that must always be executed, such as closing a file.

Example

public class Main {
public static void main(String[] args) {
try {
int arr[] = {1,2,3,4,5};
// Code that may throw an exception
System.out.println(arr[10]); // This statement will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
// Code to handle ArrayIndexOutOfBoundsException
System.out.println("ArrayIndexOutOfBoundsException");
} finally {
// Code that is always executed
System.out.println("finally block");
}
}
}

Explanation

  • Lines 7–10: The error ArrayIndexOutOfBoundsException is thrown when trying to access an element of the array with an index that is out of bounds. The exception is caught by the catch block.
  • Lines 10–13: The finally block is executed afterward.

Output

The output of the code above will be:

ArrayIndexOutOfBoundsException
finally block
Output of the above code

Free Resources