Nested try statement or block in Java

Rumman Ansari   Software Engineer   2019-03-30   9647 Share
☰ Table of Contents

Table of Content:


Nested try Statements

The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception.

Why use nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.

Syntax

....  
try  
{  
    statement 1;  
    statement 2;  
    try  
    {  
        statement 1;  
        statement 2;  
    }  
    catch(Exception e)  
    {  
    }  
}  
catch(Exception e)  
{  
}  
....  

Example Program

class NestedExcep
{
 public static void main(String[] args)
 {
  try
  {
   int arr[]={1,0,4,2};
   try
   {
    int x=arr[3]/arr[1];
   }
   catch(ArithmeticException ae)
   {
    System.out.println("divide by zero");
   }
   arr[4]=3;
  }
  catch(ArrayIndexOutOfBoundsException e)
  {
   System.out.println("array index out of bound exception");
  }
 }
}
divide by zero
array index out of bound exception
Press any key to continue . . .

Example Program2

// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;

/* If no command-line args are present, the following statement will generate
a divide-by-zero exception. */

int b = 42 / a;

System.out.println("a = " + a);

try { // nested try block

/* If one command-line arg is used, then a divide-by-zero exception
will be generated by the following code. */

if(a==1) a = a/(a-a); // division by zero
	/* If two command-line args are used, then generate an out-of-bounds exception. */
if(a==2) {
	int c[] = { 1 };
	c[42] = 99; // generate an out-of-bounds exception
	}
} catch(ArrayIndexOutOfBoundsException e) {
	System.out.println("Array index out-of-bounds: " + e);
}

} catch(ArithmeticException e) {
	System.out.println("Divide by 0: " + e);
	}
}
}

Divide by 0: java.lang.ArithmeticException: / by zero
Press any key to continue . . .

Nesting of try statements can occur in less obvious ways when method calls are involved. For example, you can enclose a call to a method within a try block. Inside that method is another try statement. In this case, the try within the method is still nested inside the outer try block, which calls the method. Here is the previous program recoded so that the nested try block is moved inside the method nesttry( ):

Example Program2 repeat

/* Try statements can be implicitly nested via
calls to methods. */
class MethNestTry {
static void nesttry(int a) {
try { // nested try block


/* If one command-line arg is used,then a divide-by-zero exception
will be generated by the following code. */

if(a==1) a = a/(a-a); // division by zero

/* If two command-line args are used,
then generate an out-of-bounds exception. */

if(a==2) {
	int c[] = { 1 };
	c[42] = 99; // generate an out-of-bounds exception
	}
} catch(ArrayIndexOutOfBoundsException e) {
	System.out.println("Array index out-of-bounds: " + e);
	}
}

public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
nesttry(a);

} catch(ArithmeticException e) {
	System.out.println("Divide by 0: " + e);
	}
  }
}
Divide by 0: java.lang.ArithmeticException: / by zero
Press any key to continue . . .

Example Program3

class NestedExcptn{
 public static void main(String args[]){
  try{
    try{
     System.out.println("going to divide");
     int b =39/0;
    }catch(ArithmeticException e){System.out.println(e);}

    try{
    int a[]=new int[5];
    a[5]=4;
    }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

    System.out.println("other statement");
  }catch(Exception e){System.out.println("handeled");}

  System.out.println("normal flow..");
 }
}
going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
other statement
normal flow..
Press any key to continue . . .