basic exception handling

I'm trying to understand exception handling, and I'm testing this simple code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
#include <stdexcept>

using namespace std;

int main()
{
    vector<int> v(4);
    try
    {
        v[v.size()] = 100;
    }
    catch(const exception& e){
        cerr << e.what() << endl;
    }
}


I expect the output to be something like:
Out of Range error: vector::_M_range_check


However, I get the same error message as if I did this:

1
2
3
4
...
vector<int> v(4);
v[v.size()] = 100;
...


that is, the usual 'non-exception-aware' code.

My question is:
What is wrong with the try catch logic I'm implementing.
operator[] does not throw exceptions, you're invoking undefined behavior.
Try v.at(v.size()) = 100;
The operator[] does not throw an exception. Read this:

http://www.cplusplus.com/reference/vector/vector/operator%5B%5D/

If the container size is greater than n, the function never throws exceptions (no-throw guarantee).
Otherwise, the behavior is undefined.
Thank you. I guess I was taking exception-being-thrown for granted.
Topic archived. No new replies allowed.