Java Nested Try Block


The try block within another try block is called nested try block.

Syntax:

try {
	statement ;
	try{
    	statement ;
    }catch (ExceptionName e){
    }    
}catch (ExceptionName e) {
  
} 

Example

public class Nestedtryblock{  
    public static void main(String args[]){  
        try{  
            try{   
                int b =1/0;  
            }catch(ArithmeticException e){
                System.out.println(e);
            }  
            try{  
                int num[] = {1, 2, 3, 4}; 
                System.out.println(num[5]); 
            }catch(ArrayIndexOutOfBoundsException e){
                System.out.println(e);
            }  
            System.out.println("Try block is sucessfully executed");  
        }
        catch(Exception e){
        	System.out.println("Exception"+e);
        }  
        System.out.println("Code flow is normal");  
    }  
} 

The nested try block used when part of the block may cause one error and the entire block might cause another error.




OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.