| Christiano <christiano@engineer.com>: Jan 24 01:55PM -0800 Please, see the code at the end of this post. Compiling and running: debian@debian:~/principles$ g++ -std=c++11 throw.cpp debian@debian:~/principles$ ./a.out 1 2 3 4 5 v[0]==1 v[1]==2 v[2]==3 v[3]==4 v[4]==5 v[5]==0 debian@debian:~/principles$ The expected output debian@debian:~/principles$ g++ -std=c++11 throw.cpp debian@debian:~/principles$ ./a.out 1 2 3 4 5 v[0]==1 v[1]==2 v[2]==3 v[3]==4 v[4]==5 Ops, range error debian@debian:~/principles$ Please, what have I done wrong? ////////// Code: ///////////// #include <iostream> #include <vector> #include <stdexcept> using namespace std; int main(void) 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) { cerr << "Ops, range error\n"; return 1; } catch(...) { cerr <<"Exception: something get wrong\n"; return 2; } |
| "Öö Tiib" <ootiib@hot.ee>: Jan 24 02:25PM -0800 On Tuesday, 24 January 2017 23:56:04 UTC+2, Christiano wrote: > Please, see the code at the end of this post. You mix things up perhaps. The 'std::vector::at' member is required to throw 'std::out_of_range' if index violates vector bounds. The behavior of program that contains 'std::vector::operator[]' call with out of bounds index is undefined. Undefined behavior may be whatever. It may output "v[5]==0" or it may crash or it may conjure demons out of your nose. Generally we avoid writing code that contains undefined behaviors. |
| ram@zedat.fu-berlin.de (Stefan Ram): Jan 24 10:03PM >Please, what have I done wrong? I suggest that you read (or re-read) the documentation of the entity that you expect to throw. |
| You received this digest because you're subscribed to updates for this group. You can change your settings on the group membership page. To unsubscribe from this group and stop receiving emails from it send an email to comp.lang.c+++unsubscribe@googlegroups.com. |
No comments:
Post a Comment