• Register
search
Log In

Std::out_of_range is defined in header file <stdexcept>

It is a class and defines a type of object to be thrown as an exception. It reports errors that are a consequence of attempting to access elements out of defined range.

 

Declaration

We can define std::out_of_range with an syntax like this class out_of_range;

 

Member functions

  • constructor → constructs a new out_of_range object with the given message.

  • Operator → replaces the out_of_range object.

  • What → returns the explanatory string.

Note : All three member functions are public member functions.

 

Std::out_of_range::out_of_range


1. out_of_range( const std:string& what_arg );

2. out_of_range( const char*  what_arg );

3. out_of_range( const out_of_range& other ) noexcept;


1 and 2 construct the exception object with what_arg as an explanatory string that can be accessed through what(). 

3 copy constructor. If *this and other both have dynamic type std::out_of_range then std::strcmp(what(), other.what()) == 0


Parameters

What_arg → explanatory string.

Other → another exception object to copy.


Exceptions 

1 and 2 may throw std::bad_alloc


Note : Because copying std::out_of_range is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking std::string&&: it would have to copy the content anyway.

 

Example

Live Demo
#include <iostream>
#include <stdexcept>
#include <vector>

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

Output 

Out of Range error: vector::_M_range_check

Conclusion

out_of_range is class which defines the type of the object. And this class give exceptions to report the error of type out_of_range.

posted Jun 23 in c++ 100 points