1

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 error\n";
        return 1;
    }
    catch (...) { // catch all other exceptions
        cerr << "Exception: something went wrong\n";
        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

AUNG
  • 39
  • 7
  • 2
    dont confuse runtime errors with c++ exceptions. `v[i]` never throws an exception when `i` is a valid index and is undefined behavior otherwise – 463035818_is_not_an_ai Mar 30 '21 at 17:00
  • 2
    Does this answer your question? https://stackoverflow.com/questions/16620222/vector-going-out-of-bounds-without-giving-error – 463035818_is_not_an_ai Mar 30 '21 at 17:01
  • So does the vector throws an exception when it goes out of bound? – AUNG Mar 30 '21 at 17:05
  • 2
    no. `v[i]` never throws an exception, unless `i` is out-of-bounds then it is [undefined behavior](https://en.cppreference.com/w/cpp/language/ub). If you want an exception you should use `at(i)` instead – 463035818_is_not_an_ai Mar 30 '21 at 17:06
  • 2
    @AUNG -- To throw an exception, the C++ code has to check the boundaries of the vector when using `[ ]`. By doing that, the code is slowed down, thus the programmer would be getting something he didn't ask for (bounds checking). Mission critical code that relies on speed would then be slowed down for no reason. If the programmer wants C++ to check the bounds, then use `at()`. Imagine a game programmer saying "Without this check for bounds, my game would be even faster". You don't want that if you're a C++ programmer. – PaulMcKenzie Mar 30 '21 at 17:17

1 Answers1

4

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 : https://godbolt.org/z/Pcv9Gn8M9

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 v.at(i) instead of v[i]. Try it here : https://godbolt.org/z/szKxhjxhx.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87