function
<exception>

std::rethrow_if_nested

template <class T>  void rethrow_if_nested (const T& e);
Rethrow if nested
Throws the exception nested in e, if (and only if) e is publicly and unambiguously derived from nested_exception.

Otherwise, the function does nothing (and does not throw).

If the nested exception is null, the function calls terminate instead.

Parameters

e
An object or reference.
If this is derived from nested_exception, the function throws the nested exception.

Return value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// throw_with_nested/rethrow_if_nested example
#include <iostream>       // std::cerr
#include <exception>      // std::exception, std::throw_with_nested, std::rethrow_if_nested
#include <stdexcept>      // std::logic_error

// recursively print exception whats:
void print_what (const std::exception& e) {
  std::cerr << e.what() << '\n';
  try {
    std::rethrow_if_nested(e);
  } catch (const std::exception& nested) {
    std::cerr << "nested: ";
    print_what(nested);
  }
}

// throws an exception nested in another:
void throw_nested() {
  try {
    throw std::logic_error ("first");
  } catch (const std::exception& e) {
    std::throw_with_nested(std::logic_error("second"));
  }
}

int main () {
  try {
    throw_nested();
  } catch (std::exception& e) {
    print_what(e);
  }

  return 0;
}

Output:

second
nested: first


Exception safety

The function may throw an exception.

See also