Open In App

Nested Try Blocks in C++

Last Updated : 28 Nov, 2023
Comments
Improve
Suggest changes
1 Like
Like
Report

In C++, a nested try block refers to the try-block nested inside another try or catch block. It is used to handle exceptions in cases where different exceptions occur in a different part of the code.

Syntax of Nested Try Blocks

The nested try/catch takes this syntax:

try
{
    // Code...... throw e2
    try
    {
        // code..... throw e1
    }
    catch (Exception e1)
    {
        // handling exception
    }
}
catch (Exception e2)
{    
    // handling exception
}

Here,

  • e1: Exception thrown in inner block.
  • e2: Exception thrown in outer block.

Example of Nested Try Blocks


Output
Throwing exception from inner try block
Inner Catch Block caught the exception
Out of the block

Explanation

Here, we used func() function to throw two exceptions of int and char type. We used an inner try block to catch integer exceptions. Now, whenever the try blocks throw an exception, the control moves outwards from the nested block till the matching catch block is found. In this case, it was the inner catch block that caught the exception.

What happens if we throw a character exception that the outer catch block is programmed to handle? Let's see,


Output
Throwing exception from inner try block
Outer catch block caught the exception
Out of the block

Here, the outer catch block caught the exception as expected.

The try blocks can also be the nested in the catch block in a similar way.


Practice Tags :

Similar Reads