Q:

Java program to implement nested try catch block

belongs to collection: Java Exception Handling Programs

0

Java program to implement nested try catch block

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will implement nested try...catch blocks to handle different kinds of exceptions.

Program/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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to get exception message using getMes... >>
<< Java program to demonstrate the throws keyword...