Trusted answers to developer questions

"Try, catch, and finally" block in Java

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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");
}
}

RELATED TAGS

try
catch
finally
java
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?