Nested Try Blocks in C++
Last Updated :
28 Nov, 2023
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
C++
#include <iostream>
using namespace std;
void func( int n)
{
if (n < 10) {
throw 22;
}
else {
throw 'c' ;
}
}
int main()
{
try {
try {
cout << "Throwing exception from inner try "
"block\n" ;
func(2);
}
catch ( int n) {
cout << "Inner Catch Block caught the exception"
<< endl;
}
}
catch ( char c) {
cout << "Outer catch block caught the exception"
<< endl;
}
cout << "Out of the block" ;
return 0;
}
|
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,
C++
#include <iostream>
using namespace std;
void func( int n)
{
if (n < 10) {
throw 22;
}
else {
throw 'c' ;
}
}
int main()
{
try {
try {
cout << "Throwing exception from inner try "
"block\n" ;
func(12);
}
catch ( int n) {
cout << "Inner Catch Block caught the exception"
<< endl;
}
}
catch ( char c) {
cout << "Outer catch block caught the exception"
<< endl;
}
cout << "Out of the block" ;
return 0;
}
|
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.
Share your thoughts in the comments
Please Login to comment...