函式
<exception>

std::throw_with_nested

[[noreturn]] template <class T>  void throw_with_nested (T&& e);
巢狀丟擲
丟擲一個異常,該異常結合了當前處理的異常e

當前處理的異常成為巢狀異常,而 e 成為外部異常

丟擲的異常型別將公開派生自 T當前處理的異常(後者作為 nested_exception 成分)。

如果 T 是引用型別,則它繼承的型別是沒有引用的型別,該型別是 T 引用的,並且必須是可複製構造的。

如果當前沒有透過 catch 塊處理異常,則巢狀異常是一個exception_ptr

引數

e
一個非聯合類物件或引用,它不派生自 nested_exception

返回值

無(該函式永不返回)。

示例

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;
}

輸出

second
nested: first


異常安全

丟擲異常。

如果引數不是正確的型別(如上所述),則該呼叫會導致未定義行為

另見