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:

Example

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

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++.

Example

#include <iostream>
using namespace std;

// function throwing exceptions
void divide(int a, int b) {
 if (b == 0) {
 throw "Division by zero is not allowed";
 } else {
 throw 42;
 }
}

// driver code
int main() {
 try {
 try {
 cout << "Throwing exception from inner try block\n";
 divide(10, 0);
 } catch (const char* error) {
 cout << "Inner Catch Block caught the exception: " << error << endl;
 }
 } catch (int result) {
 cout << "Outer catch block caught the exception: " << result << endl;
 }

 cout << "Out of the block";

 return 0;
}

Output:

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:

Example

#include <iostream>
using namespace std;

// function throwing exceptions
void divide(int a, int b) {
 if (b == 0) {
 throw "Division by zero is not allowed";
 } else {
 throw 'X';
 }
}

// driver code
int main() {
 try {
 try {
 cout << "Throwing exception from inner try block\n";
 divide(8, 0);
 } catch (const char* error) {
 cout << "Inner Catch Block caught the exception: " << error << endl;
 }
 } catch (char symbol) {
 cout << "Outer catch block caught the exception: " << symbol << endl;
 }

 cout << "Out of the block";

 return 0;
}

Output:

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.

Input Required

This code uses input(). Please provide values below: