Nested Try block in Java

Posted in /  

Nested Try block in Java

    Java allows you to declare one try block within another try block. Nested try blocks are used when a part of the try block throws one exception, and the complete try block throws another exception; thus, nested try blocks are used.

    Syntax

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

    Example

    import java.util.regex.*;  
    public class Simple{  
    public static void main(String args[]){  
    try{  
        try{  
         System.out.println("going to divide");  
         int b =48/0;  
        }catch(ArithmeticException e){System.out.println(e);}  
        try{  
        int a[]=new int[10];  
        a[10]=6; 
        }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);} 
        System.out.println("code");  
      }catch(Exception e){System.out.println("handeled");}  
      System.out.println("normal program flow");  
     }  
    }     

    Output

    Nested try block

    Conclusion

    So this was all about the nested try block in Java. In this tutorial, we have explained a nested try block in Java with one simple example and its output to help you get a better grip on the topic. If you have any queries, feel free to share them in the comments section below.

    People are also reading:

    Ramya
    Written by

    Ramya Shankar

    A cheerful, full of life and vibrant person, I hold a lot of dreams that I want to fulfill on my own. My passion for writing started with small diary entries and travel blogs, after which I have moved on to writing well-researched technical content. I find it fascinating to blend thoughts and research and shape them into something beautiful through my writing.