C++ 庫 - <exception>



介紹

這是一個標準異常類。標準庫元件丟擲的所有物件都派生自此類。因此,可以透過引用捕獲此型別來捕獲所有標準異常。

宣告

以下是 std::exception 的宣告。

class exception;

示例

以下為 std::exception 的示例。

#include <thread>
#include <vector>
#include <iostream>
#include <atomic>
 
std::atomic_flag lock = ATOMIC_FLAG_INIT;
 
void f(int n) {
   for (int cnt = 0; cnt < 100; ++cnt) {
      while (lock.test_and_set(std::memory_order_acquire))
         ;
      std::cout << "Output from thread " << n << '\n';
      lock.clear(std::memory_order_release);
   }
}
 
int main() {
   std::vector<std::thread> v;
   for (int n = 0; n < 10; ++n) {
      v.emplace_back(f, n);
   }
   for (auto& t : v) {
      t.join();
   }
}

派生型別

序號 派生型別 定義
1 bad_alloc 記憶體分配失敗時丟擲此異常
2 bad_cast 動態轉換失敗時丟擲此異常
3 bad_exception 由 unexpected 處理程式丟擲的異常
4 bad_function_call 錯誤呼叫時丟擲此異常
5 bad_typeid 空指標的 typeid 時丟擲此異常
6 bad_weak_ptr 這是一個無效的弱指標
7 ios_base::failure 它是流異常的基類
8 logic_error 這是一個邏輯錯誤異常
9 runtime_error 這是一個執行時錯誤異常

派生型別(透過 logic_error)

序號 派生型別 定義
1 domain_error 這是一個域錯誤異常
2 future_error 這是一個 future 錯誤異常
3 invalid_argument 這是一個無效引數異常
4 length_error 這是一個長度錯誤異常
5 out_of_range 這是一個超出範圍異常

派生型別(透過 runtime_error)

序號 派生型別 定義
1 overflow_error 這是一個溢位錯誤異常
2 range_error 這是一個範圍錯誤異常
3 system_error 這是一個系統錯誤異常
4 underflow_error 這是一個下溢錯誤異常

派生型別(透過 bad_alloc)

序號 派生型別 定義
1 bad_array_new_length 陣列長度錯誤時丟擲的異常

派生型別(透過 system_error,自 C++11 起)

序號 派生型別 定義
1 ios_base::failure 它是流異常的基類

成員函式

序號 派生型別 定義
1 (建構函式) 這是一個建構函式異常
2 operator= 這是一個複製異常
3 what 用於獲取標識異常的字串
4 (解構函式) 這是一個銷燬異常
廣告