Rethrowing exceptions in C++

Level 4190 keystrokes

An inner catch block handles a runtime_error, prints it and rethrows it with throw;, so the outer catch block receives the same exception.

C++ code

// Outer try block
1try {
// Inner try block
2 try {
// Throw a runtime_error with a message
3 throw runtime_error("Inner error");
// Catch by reference to the base class exception
4 } catch (exception& e) {
// what() returns the message: prints Caught: Inner error
5 cout << "Caught: " << e.what() << endl;
// throw; with no operand rethrows the same exception object
6 throw;
7 }
// The outer block catches the rethrown exception
8} catch (exception& e) {
// Same message: prints Rethrown: Inner error
9 cout << "Rethrown: " << e.what() << endl;
10}

Output

Caught: Inner error
Rethrown: Inner error
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 12
  • "× 6
  • (× 5
  • )× 5
  • ;× 4
  • {× 4
  • }× 4
  • :× 2
  • .× 2
  • &× 2

More C++ examples at level 4

← C++ typing practice