Hi everyone in this blog I’m explaining about nested try block in java. The try block within a try block is known as nested try block in java. 

Details:

One try-catch block can be present in the another try’s body. This is called nesting of try-catch blocks. Each time a try block does not have a catch handler for a particular exception the stack is unwound and the next try block’s catch handlers are inspected for a match.

Exception handlers can be nested within one another. A try, catch or a finally block can, in turn, contains another set of try catch finally sequences. In such a scenario, when a particular catch block is unable to handle an Exception, this exception is rethrown. This exception would be handled by the outer set of try catch handler. Look at the following code for Example.

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;
    Statement;
    try
    {
       Statement;
       Statement;
    }
    catch(Exception ex)
    {
    }
}
catch(Exception ex)
{ }

Java nested try the example:

class Excep6

{
    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..");
    }
}

check more post on exception handling here

  Modified On Feb-26-2018 12:20:00 AM

Leave Comment