Practical-43
Write a java program which uses Nested try Statements.
Introdution
In Java, nested try blocks are when one try block is placed inside the body of another try block. This allows the program to handle exceptions from a variety of sources by nesting try blocks, catching different types of exceptions within different try blocks. For example, an outer try block can contain a nested try block and catch any exceptions that were not handled in the nested block. Additionally, a nested try block is especially useful for code that can generate multiple kinds of exceptions, allowing the code to test for each exception and react to each one appropriately.
Code
public class NestedTryExample
{
public static void main(String[] args) {
// Outer try-catch block
try
{
// Nested try block
try
{
// Generate an array index out of bound exception
int arr[] = {50,60,70};
System.out.println(arr[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception handled");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception handled");
}
catch(Exception e)
{
System.out.println("Exception handled");
}
finally
{
System.out.println("Finally block executed");
}
System.out.println("Next statement after nested try (Inside outer try)");
}
catch(Exception e)
{
System.out.println("Caught in outer try-catch block");
}
}
}
Output
ArrayIndexOutOfBounds Exception handled Finally block executed Next statement after nested try (Inside outer try)
Explanation
This Java example is a minimal example of how to handle exceptions using nested try blocks. It contains two try blocks: an outer one surrounding the nested one. Within the nested try block, the code attempts to generate an array index out of bounds exception by attempting to print out the tenth element of an array of only three. The first catch block handles any arithmetic exceptions, the second any array index out of bounds exceptions, and the last any other exceptions. This example also illustrates the use of the finally block, which will be executed both after the completion of the try block and after the completion of any of the catch blocks (if they are executed).