Nested Try Blocks in C++

In this article, we will discuss the nested try blocks in C++ with its syntax and examples.

What is Nested Try Blocks?

The term "nested try block" in C++ describes a try-block that is nestled inside another try or catch block. When distinct exceptions arise in various places within the code, it is utilized to handle them.

Structure of Nesting Try Blocks:

Here is the syntax for the nested try/catch:

In this case,

e1: The inner block threw an exception.

e2: The outer block has an exception thrown.

Example of Nested Try Blocks:

Let us take an example to illustrate the nested try blocks in C++.

Output:

Throwing exception from inner try block
Inner Catch Block caught the exception: Division by zero is not allowed
Out of the block

Explanation:

Here, two exceptions of the int and char types were thrown using the func() function. We implemented an inner try block to handle integer exceptions. Currently, the control leaves the nested block and expands outward until it finds the corresponding catch block anytime one of the try blocks throws an exception. In this instance, the exception was captured by the inner catch block.

As the outer catch block is designed to handle, we will see what happens if we throw a character exception.

Example:

Output:

Throwing exception from inner try block
Inner Catch Block caught the exception: Division by zero is not allowed
Out of the block

Explanation:

In this case, the exception was correctly captured by the outer catch block.

In the same manner, the try blocks can also be nested inside the catch block.






Latest Courses