1
2#include <iostream>
3#include <stdexcept>
4#include <vector>
5
6int main (void) {
7 std::vector<int> myvector(10);
8 try {
9 myvector.at(20)=100; // vector::at throws an out-of-range
10 }
11 catch (const std::out_of_range& oor) {
12 std::cerr << "Out of Range error: " << oor.what() << '\n';
13 }
14 return 0;
15}
1Defines a type of object to be thrown as exception.
2It reports errors that are consequence of attempt to access elements out of
3defined range.
4
5It may be thrown by the member functions of std::bitset and std::basic_string,
6by std::stoi and std::stod families of functions,
7and by the bounds-checked member access functions
8(e.g. std::vector::at and std::map::at).
1class out_of_range : public logic_error {
2public:
3 explicit out_of_range (const string& what_arg);
4};
5
6EX.
7
8// out_of_range example
9#include <iostream> // std::cerr
10#include <stdexcept> // std::out_of_range
11#include <vector> // std::vector
12
13int main (void) {
14 std::vector<int> myvector(10);
15 try {
16 myvector.at(20)=100; // vector::at throws an out-of-range
17 }
18 catch (const std::out_of_range& oor) {
19 std::cerr << "Out of Range error: " << oor.what() << '\n';
20 }
21 return 0;
22}
1Replace throw std::out_of_range; with throw std::out_of_range ("blah");. I.e. you need to create an object, you cannot throw a type.