ADVERTISEMENT
ADVERTISEMENT

Java program to implement nested try catch block

Java example to implement nested try catch block.
Submitted by Nidhi, on April 20, 2022

Problem Solution:

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

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.