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
tryblock is used to specify a block of code that may throw an exception. - The
catchblock is used to handle the exception if it is thrown. - The
finallyblock is used to execute the code after thetryandcatchblocks 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
tryblock contains the code that may throw an exception. If an exception is thrown in thetryblock, the code in thecatchblock is executed. - Lines 5–7: The
catchblock contains the code that handles theException. The order of thetry,catch, andfinallyblocks is important. If we place thefinallyblock before thecatchblock, the code will not compile. - Lines 7–8: The
finallyblock contains the code that is always executed. Thefinallyblock 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 exceptionSystem.out.println(arr[10]); // This statement will throw ArrayIndexOutOfBoundsException} catch (ArrayIndexOutOfBoundsException e) {// Code to handle ArrayIndexOutOfBoundsExceptionSystem.out.println("ArrayIndexOutOfBoundsException");} finally {// Code that is always executedSystem.out.println("finally block");}}}
Explanation
- Lines 7–10: The error
ArrayIndexOutOfBoundsExceptionis thrown when trying to access an element of the array with an index that is out of bounds. The exception is caught by thecatchblock. - Lines 10–13: The
finallyblock is executed afterward.
Output
The output of the code above will be:
ArrayIndexOutOfBoundsExceptionfinally block
Output of the above code