函式
<exception>

std::current_exception

exception_ptr current_exception() noexcept;
獲取當前異常的智慧指標
返回一個指向當前處理的異常或其副本的 exception_ptr 物件。

如果沒有處理任何異常,該函式將返回一個*空指標*值。

exception_ptr 是一個共享的*智慧指標*型別:只要至少有一個 exception_ptr 指向它,所指向的異常就保證保持有效,這可能會延長所指向異常物件的生命週期,使其超出其作用域或跨越執行緒。有關更多資訊,請參閱 exception_ptr

此函式不丟擲異常,但如果該函式實現為返回一個指向*當前處理的異常*的*副本*的指標,則在無法分配儲存空間(bad_alloc)或複製過程失敗時(如果可能,則返回丟擲的異常或 bad_exception;否則返回其他未指定的值),它可能會返回一個指向不同異常的指標。

引數



返回值

一個指向*當前處理的異常*的 exception_ptr 物件,或者在函式內部過程會引發新異常時指向另一個異常。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// exception_ptr example
#include <iostream>       // std::cout
#include <exception>      // std::exception_ptr, std::current_exception, std::rethrow_exception
#include <stdexcept>      // std::logic_error

int main () {
  std::exception_ptr p;
  try {
     throw std::logic_error("some logic_error exception");   // throws
  } catch(const std::exception& e) {
     p = std::current_exception();
     std::cout << "exception caught, but continuing...\n";
  }

  std::cout << "(after exception)\n";

  try {
     std::rethrow_exception (p);
  } catch (const std::exception& e) {
     std::cout << "exception caught: " << e.what() << '\n';
  }
  return 0;
}

輸出

exception caught, but continuing...
(after exception)
exception caught: some logic_error exception


資料競爭

該函式是返回一個指向*當前處理的異常*的物件還是其副本,取決於具體的庫實現。

異常安全

無丟擲保證:此函式不丟擲異常。相反,此函式使用其返回值來指示在其內部操作過程中丟擲的異常。

另見