<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


异常安全

强保证: 如果构造函数抛出异常,则没有副作用。

另见