"Try, catch, and finally" block in Java

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:

  1. Scenario 1: In this scenario, the exception occurs in the try block and is dealt with in the catch block.​

  2. Scenario 2: In this scenario, the exception occurs in the try block and is not dealt with in the catch block.

  3. Scenario 3: No exception occurs in the try block.

Code

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 executes
System.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 executed
System.out.println("Program is outside the try-catch-finally clause");
}
}
Copyright ©2024 Educative, Inc. All rights reserved