<stdexcept>

std::length_error

class length_error;
Length error exception

This class defines the type of objects thrown as exceptions to report a length error.

It is a standard exception that can be thrown by programs. Some components of the standard library, such as vector and string also throw exceptions of this type to signal errors resizing.

It is defined as
1
2
3
4
class length_error : public logic_error {
public:
  explicit length_error (const string& what_arg);
};
1
2
3
4
5
class length_error : public logic_error {
public:
  explicit length_error (const string& what_arg);
  explicit length_error (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
16
// length_error example
#include <iostream>       // std::cerr
#include <stdexcept>      // std::length_error
#include <vector>         // std::vector

int main (void) {
  try {
    // vector throws a length_error if resized above max_size
    std::vector<int> myvector;
    myvector.resize(myvector.max_size()+1);
  }
  catch (const std::length_error& le) {
	  std::cerr << "Length error: " << le.what() << '\n';
  }
  return 0;
}

可能的輸出

Length error: vector::_M_fill_insert


異常安全

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

另見