Home »
Java »
Java Programs
Java program to implement nested try catch block
Java example to implement nested try catch block.
Submitted by Nidhi, on April 20, 2022
Problem statement
In this program, we will implement nested try...catch blocks to handle different kinds of exceptions.
Source Code
The source code to implement the nested try catch block is given below. The given program is compiled and executed successfully.
// Java program to demonstrate nested try block
public class Main {
public static void main(String[] args) {
// Outer catch
try {
// Inner block to handle
// ArrayIndexOutOfBoundsException
try {
int array[] = new int[10];
array[10] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception: " + e);
}
try {
int div = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception: " + e);
}
System.out.println("Statement in outer try block.");
} catch (Exception e) {
System.out.println("Outer catch to handle other exception.");
}
System.out.println("Program finished");
}
}
Output
Exception: java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
Exception: java.lang.ArithmeticException: / by zero
Statement in outer try block.
Program finished
Explanation
In the above program, we created a class Main. The Main class contains the main() method.
The main() method is the entry point for the program. And, implemented nested try... catch blocks to handle ArtihmeticException, ArrayIndexOutOfBoundException, and also other exceptions and printed appropriate messages.
Java Exception Handling Programs »