C++/STL Basics/out of range exception

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Access out-of-range element

<source lang="cpp">

  1. include <iostream>

using std::cout; using std::endl;

  1. include <vector> // vector class-template definition
  2. include <algorithm> // copy algorithm
  3. include <iterator> // ostream_iterator iterator
  4. include <stdexcept> // out_of_range exception

int main() {

  int array[ 6 ] = { 1, 2, 3, 4, 5, 6 };
  std::vector< int > integers( array, array + 6 );
  std::ostream_iterator< int > output( cout, " " );
  integers.push_back( 2 );
  integers.push_back( 3 );
  integers.push_back( 4 );
  cout << "Vector integers contains: ";
  std::copy( integers.begin(), integers.end(), output );
  try
  {
     integers.at( 100 ) = 777;
  } catch ( std::out_of_range outOfRange ) // out_of_range exception
  {
     cout << "\n\nException: " << outOfRange.what();
  }
  return 0;

}

/* 

Vector integers contains: 1 2 3 4 5 6 2 3 4 Exception: vector::_M_range_check

*/       
 </source>


Catch out_of_range exception

<source lang="cpp">


  1. include <iostream>
  2. include <vector>
  3. include <exception>
  4. include <stdexcept> // out_of_range exception

using namespace std; int main( ) {

 char carr[] = {"a", "b", "c", "d", "e"};
 vector<char> v;
 v.push_back("a");
 v.push_back("b");
 v.push_back("c");
 v.push_back("d");
 v.push_back("e");
 try {
   cout << v.at(10000) << "\n";
 } catch(std::out_of_range& e) {
   cerr << e.what( ) << "\n";
 }

}

 </source>


Use std::out_of_range Exception for vector

<source lang="cpp">

  1. include <iostream>

using std::cout; using std::endl;

  1. include <vector> // vector class-template definition
  2. include <algorithm> // copy algorithm
  3. include <iterator> // ostream_iterator iterator
  4. include <stdexcept> // out_of_range exception

int main() {

  int array[ 6 ] = { 1, 2, 3, 4, 5, 6 };
  std::vector< int > integers( array, array + 6 );
  std::ostream_iterator< int > output( cout, " " );
  integers.push_back( 2 );
  integers.push_back( 3 );
  integers.push_back( 4 );
  cout << "Vector integers contains: ";
  std::copy( integers.begin(), integers.end(), output );
  try
  {
     integers.at( 100 ) = 777;
  } catch ( std::out_of_range outOfRange ) // out_of_range exception
  {
     cout << "\n\nException: " << outOfRange.what();
  }
  return 0;

}

 /* 

Vector integers contains: 1 2 3 4 5 6 2 3 4 Exception: vector::_M_range_check

*/      
 </source>