<exception>

std::nested_exception

class nested_exception;
巢狀異常類
一種異常類的元件,它可以捕獲當前處理的異常作為巢狀異常。

一個類,該類同時派生自此類和另一個異常類,它可以儲存這兩個異常的屬性:當前處理的異常(作為其巢狀異常)和另一個異常(其外部異常)。

通常透過呼叫帶有一個外部異常物件作為引數的 throw_with_nested 來構造具有巢狀異常的物件。返回的物件具有與外部異常相同的屬性和成員,但攜帶與巢狀異常相關的附加資訊,幷包含兩個成員函式來訪問此巢狀異常nested_ptrrethrow_nested

其宣告如下:
1
2
3
4
5
6
7
8
9
10
class nested_exception {
public:
  nested_exception() noexcept;
  nested_exception (const nested_exception&) noexcept = default;
  nested_exception& operator= (const nested_exception&) noexcept = default;
  virtual ~nested_exception() = default;

  [[noreturn]] void rethrow_nested() const;
  exception_ptr nested_ptr() const noexcept;
}

成員函式


複製賦值和虛解構函式是顯式預設的。

示例

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
// nested_exception 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