<stdexcept>

std::out_of_range

class out_of_range;
越界異常

此類定義了用於報告越界錯誤的異常物件的型別。

它是一個可以被程式丟擲的標準異常。標準庫的一些元件,例如 vectordequestringbitset,也會丟擲此類異常來指示引數超出範圍。

它被定義為
1
2
3
4
class out_of_range : public logic_error {
public:
  explicit out_of_range (const string& what_arg);
};
1
2
3
4
5
class out_of_range : public logic_error {
public:
  explicit out_of_range (const string& what_arg);
  explicit out_of_range (const char* what_arg);
};

成員

建構函式
傳遞給 what_arg 的字串與成員 what 返回的值內容相同。

此類從 logic_error 繼承了 what 成員函式。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// out_of_range example
#include <iostream>       // std::cerr
#include <stdexcept>      // std::out_of_range
#include <vector>         // std::vector

int main (void) {
  std::vector<int> myvector(10);
  try {
    myvector.at(20)=100;      // vector::at throws an out-of-range
  }
  catch (const std::out_of_range& oor) {
    std::cerr << "Out of Range error: " << oor.what() << '\n';
  }
  return 0;
}

可能的輸出

Out of Range error: vector::_M_range_check


異常安全

強保證: 如果建構函式丟擲異常,則沒有副作用。

另見