Nested Try Blocks In Java

We can use nested try block in java.

Syntax:1

try {

// some statement
try {

// some statement
} catch (Exception e) {

}

} catch (Exception e) {

}

Syntax:2


try{

display();

}catch(){

}

void display(){

try{

}catch(){

}

}





1. 

public class NestedTry {


public static void main(String[] args) {


try {
 
System.out.println(“Outer Try”);
int []arr=new int[5];
arr[10]=100;
try {
System.out.println(“Inner Try”);
int i=100/0;
} catch (Exception e) {
System.out.println(e);
}

} catch (Exception e) {
System.out.println(e);
}


}



}

Output:

Outer Try
java.lang.ArrayIndexOutOfBoundsException: 10

Explanation: See This  Interesting Facts In Exception Handling In java

2.

package exception_handling;
public class NestedTry {
public static void main(String[] args) {
try {
System.out.println(“Outer Try”);
int []arr=new int[5];
try {
System.out.println(“Inner Try”);
int i=100/0;
} catch (Exception e) {
System.out.println(e);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
Outer Try
Inner Try
java.lang.ArithmeticException: / by zero

3.

package exception_handling;
public class NestedTry {
void divideNumber(){
try {
System.out.println(“In divide number”);
int j=10/0;
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
try {
System.out.println(“Outer Try”);
  int []arr=new int[5];
           NestedTry nestedtry=new NestedTry();
           nestedtry.divideNumber();
} catch (Exception e) {
System.out.println(e);
}
}
}

Output:

Outer Try
In divide number
java.lang.ArithmeticException: / by zero

Leave a Reply

Your email address will not be published. Required fields are marked *

8 + = 13