Nested try-catch

Nested try-catch Blocks in C++

IntermediateTopic: Exception Handling Programs
Back

C++ Nested try-catch Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <stdexcept>
using namespace std;

void innerFunction(int level) {
    if (level == 1) {
        throw runtime_error("Error at level 1");
    }
    if (level == 2) {
        throw invalid_argument("Error at level 2");
    }
    cout << "Level " << level << " processed successfully" << endl;
}

void outerFunction(int level) {
    try {
        cout << "Outer try: Processing level " << level << endl;
        
        try {
            cout << "Inner try: Calling innerFunction" << endl;
            innerFunction(level);
        } catch (const invalid_argument& e) {
            cout << "Inner catch: " << e.what() << " (handled)" << endl;
            // Re-throw to outer catch
            throw;
        }
        
        cout << "Outer try: After inner try-catch" << endl;
    } catch (const runtime_error& e) {
        cout << "Outer catch: " << e.what() << " (handled)" << endl;
    }
}

int main() {
    cout << "=== Test 1: Error at level 1 ===" << endl;
    outerFunction(1);
    
    cout << "\n=== Test 2: Error at level 2 ===" << endl;
    outerFunction(2);
    
    cout << "\n=== Test 3: No error ===" << endl;
    outerFunction(3);
    
    return 0;
}
Output
=== Test 1: Error at level 1 ===
Outer try: Processing level 1
Inner try: Calling innerFunction
Outer catch: Error at level 1 (handled)

=== Test 2: Error at level 2 ===
Outer try: Processing level 2
Inner try: Calling innerFunction
Inner catch: Error at level 2 (handled)
Outer catch: std::invalid_argument (handled)

=== Test 3: No error ===
Outer try: Processing level 3
Inner try: Calling innerFunction
Level 3 processed successfully
Outer try: After inner try-catch

Understanding Nested try-catch

Nested try-catch blocks allow handling exceptions at different levels. Inner catch can handle exception or re-throw using throw. Re-thrown exceptions propagate to outer catch blocks. Useful for handling errors at appropriate abstraction levels. Inner catch can transform exception type before re-throwing.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents