Cant catch out_of_range

So Im learning "exceptions" and heres my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 


int main(){
          cout << "\n";
          try{

     vector<int> v;

     for (int x; cin >> x; )
          {
            v.push_back(x);
          } 

          for (int i = 0; i <= v.size(); ++i)
          {
            cout << "v[" << i << "] = " << v[i] << "\n";
          }
          
     }
catch(out_of_range){
     cout << "outta range"; return 1;
}

catch(...){
     cout << "somethin else"; return 2;
}
     cout << "\n";
    



so in spite of i <= v.size() mistake, why is it not catching out of range exception?
Last edited on
Because operator[] doesn't do range checking so no exceptions are ever thrown. If you want an out_of_range exception to be thrown when you use an invalid index you should use the at function instead.

 
cout << "v[" << i << "] = " << v.at(i) << "\n";

http://www.cplusplus.com/reference/vector/vector/at/
Have you read the vector::operator[] reference page?
http://www.cplusplus.com/reference/vector/vector/operator[]/

The vector operator [] is not bounds checked. So don't expect it to throw an exception.

A similar member function, vector::at, has the same behavior as the operator [] function, except that vector::at is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception.
Last edited on
Topic archived. No new replies allowed.