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:
try block is used to specify a block of code that may throw an exception. catch block is used to handle the exception if it is thrown. finally block is used to execute the code after the try and catch blocks have been executed.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}}}
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. 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. 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.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");}}}
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.finally block is executed afterward.The output of the code above will be:
ArrayIndexOutOfBoundsExceptionfinally block