Does “try-catch” catches run time error (especially Out of Range error)

I’m following an example code from Programming Principles and Practice Using C++ in one of the example for exception it shows this snippet of code

int main()
    try {
        vector<int> v; // a vector of ints
        for (int x; cin >> x; )
            v.push_back(x); // set values
        for (int i = 0; i <= v.size(); ++i) // print values
            cout << "v[" << i << "] == " << v[i] << 'n';
    catch (const out_of_range& e) {
        cerr << "Oops! Range errorn";
        return 1;
    catch (...) { // catch all other exceptions
        cerr << "Exception: something went wrongn";
        return 2;

From what I understand it is suppose to catch out_of_range error and output “Oops! Range error”. However, the Visual Studio 2019 shows this instead.

enter image description here

can someone explain why it shows me this


Does “try-catch” catches run time error (especially Out of Range error)?

No, in C++ most run time errors lead to Undefined Behavior, not exceptions. Only errors which explicitly throw exceptions can be caught.

std::vector<T>::operator[] does not specify that it throws an exception when you access out of bounds, it is just Undefined Behavior and anything can happen. It can even appear to work. When I try it here, there isn’t any visible error :

If you want an exception on out of bounds access, std::vector<T>::at() does throw std::out_of_range.

For your test you should use instead of v[i]. Try it here :