Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Nested try-catch in C++

Nested try-catch in C++: an inner handler catches one type and rethrows with throw;, the outer handler catches the rest, and why the base class matters there.

IntermediateException Handling ProgramsExample 5 of 5
nested-try-catch.cpp
1#include <iostream>
2#include <stdexcept>
3using namespace std;
4
5void innerFunction(int level) {
6 if (level == 1) {
7 throw runtime_error("Error at level 1");
8 }
9 if (level == 2) {
10 throw invalid_argument("Error at level 2");
11 }
12 cout << "Level " << level << " processed successfully" << endl;
13}
14
15void outerFunction(int level) {
16 try {
17 cout << "Outer try: Processing level " << level << endl;
18
19 try {
20 cout << "Inner try: Calling innerFunction" << endl;
21 innerFunction(level);
22 } catch (const invalid_argument& e) {
23 cout << "Inner catch: " << e.what() << " (handled)" << endl;
24 // Re-throw to outer catch
25 throw;
26 }
27
28 cout << "Outer try: After inner try-catch" << endl;
29 } catch (const exception& e) {
30 cout << "Outer catch: " << e.what() << " (handled)" << endl;
31 }
32}
33
34int main() {
35 cout << "=== Test 1: Error at level 1 ===" << endl;
36 outerFunction(1);
37
38 cout << "\n=== Test 2: Error at level 2 ===" << endl;
39 outerFunction(2);
40
41 cout << "\n=== Test 3: No error ===" << endl;
42 outerFunction(3);
43
44 return 0;
45}

Sample Output

Inner catch: Error at level 2 (handled)

The inner handler ran first.

Outer catch: Error at level 2 (handled)

The rethrown exception reached the outer handler.

In this one

  • How exceptions move from an inner try to an outer one
  • What a bare throw; does
  • Why the outer catch must match the rethrown type
  • How the standard exception hierarchy fits together

How it works

  1. 1

    Level 1: runtime_error skips the inner catch; the outer catch prints it.

  2. 2

    Level 2: the inner catch prints and rethrows; the outer catch prints it too.

  3. 3

    Level 3: no exception; every line prints.

Dry run: Nested try-catch

Level 2

  1. 1.Outer try → Inner try → innerFunction throws invalid_argument
  2. 2.Inner catch (invalid_argument) prints, then throw;
  3. 3."After inner try-catch" skipped
  4. 4.Outer catch (exception&) prints "Error at level 2 (handled)"
Level 2
Outer try → Inner try → innerFunction throws invalid_argument
Inner catch (invalid_argument) prints, then throw;
"After inner try-catch" skipped
Outer catch (exception&) prints "Error at level 2 (handled)"

Edge cases

Outer catch too narrow

Change the outer handler back to catch (const runtime_error& e).

The rethrown invalid_argument matches nothing, so std::terminate ends the program during Test 2.

throw e; instead of throw;

Rethrow with throw e; in the inner catch.

It throws a copy of type invalid_argument, which works here, but if e were caught as a base class the copy would be sliced to the base type. throw; keeps the original.

Bare throw outside a catch

Call throw; when no exception is active.

std::terminate is called.

What's going on

A try-catch can sit inside another try. The inner block handles what it can, and anything it does not handle, or chooses to pass on, moves out to the outer block.

innerFunction throws runtime_error at level 1, invalid_argument at level 2, and succeeds at level 3.

The inner try in outerFunction only catches invalid_argument. The outer try catches const exception&, which covers every standard exception.

Test 1: runtime_error does not match the inner handler, so it passes straight out to the outer catch. The line "Outer try: After inner try-catch" is skipped.

Test 2: invalid_argument matches the inner handler, which prints its message and then runs throw; with nothing after it. A bare throw; rethrows the exception currently being handled, keeping the original object and type. The outer catch receives it and prints "Error at level 2".

Test 3: nothing is thrown, so neither handler runs and both "processed successfully" and "After inner try-catch" print.

A correction was needed here. The original program's outer handler was catch (const runtime_error& e). invalid_argument does not derive from runtime_error (it derives from logic_error), so in Test 2 the rethrown exception matched nothing, and the program terminated before Test 3 ever ran. Changing the outer handler to const exception&, the shared base class, makes the program do what its sample output describes.

Rethrowing like this is common when an inner layer wants to log or clean up but leave the final decision to its caller.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <stdexcept> is there because it provides standard exception classes. Leave one out and the compiler stops at the first name it does not recognize.

Understanding Nested try-catch

Nested Concept:

try-catch inside another try-catch
Multiple levels of handling
Inner can handle or re-throw
Outer handles if inner doesn't

Exception Flow:

Exception thrown in inner try
Inner catch can handle
Or re-throw to outer
Outer catch handles if re-thrown

Inner try-catch Block

Structure:

try {

try {

// Inner code

} catch (const SomeException& e) {

// Inner catch

}

} catch (const OtherException& e) {

// Outer catch

}

What happens here:

Inner try-catch handles first
Can catch specific types
Can re-throw if needed
Outer handles if not caught

Re-throwing Exceptions

Using throw:

catch (const invalid_argument& e) {

cout << "Inner catch: " << e.what() << endl;

throw; // Re-throw to outer

}

What happens here:

throw; re-throws same exception
Propagates to outer catch
Preserves exception type
Enables multi-level handling

Exception Propagation

Flow Example:

1.Exception thrown in inner try
2.Inner catch handles or re-throws
3.If re-thrown, outer catch handles
4.Program continues after outer catch

What happens here:

Exceptions propagate upward
Each level can handle
Or pass to next level
Hierarchical error handling

When to Use Nested try-catch

Good fits:

Multi-level error handling
Different abstraction levels
Local error recovery
Hierarchical error management
Transforming exceptions

Example Scenarios:

Function call chains
Library and application levels
Different error contexts
Error transformation
Multi-level recovery

Important Considerations

Catch Order:

Inner catch handles first
Outer catch handles if re-thrown
Specific before general
Order matters

Re-throwing:

Use throw; to re-throw
Preserves exception type
Can transform before re-throw
Enables multi-level handling

Error Context:

Each level adds context
Better error messages
Appropriate handling level
Clear error semantics

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does a bare throw; inside a catch do?

Pick an answer to check it.

Question 2

In the original code, why did Test 2 terminate?

Pick an answer to check it.

Questions people ask

When should I rethrow?

When you can do part of the job, such as logging or cleanup, but the caller should decide what happens next.

Can I throw a different exception from a catch?

Yes. Use std::throw_with_nested if you want to keep the original too.

Does code after the inner try still run?

Only when the inner block finishes or its handler does not rethrow.