The try, catch, and finally block in Java is used to handle exceptions in the Java language.
Finally
is used to implement something specific in the code; it is not dependent on the try-catch block and is always implemented.
To handle exceptions, a programmer creates three blocks based on three scenarios:
Scenario 1: In this scenario, the exception occurs in the try
block and is dealt with in the catch
block.
Scenario 2: In this scenario, the exception occurs in the try
block and is not dealt with in the catch
block.
Scenario 3: No exception occurs in the try
block.
All three blocks are executed in the following code:
class main{public static void main (String[] args){int[] myArr = new int[10];try{int i = myArr[10]; // exception occurs array assigned to int variable.//this statement never executesSystem.out.println("Program is inside the try block");}catch(ArrayIndexOutOfBoundsException ex){System.out.println("Exception has been caught in the catch block");}finally{System.out.println("Now the finally block is executed");}// rest of the program will be executedSystem.out.println("Program is outside the try-catch-finally clause");}}