1

I am not sure what silly mistake I am making but I am expecting an out-of-range error in the following code but it just prints values of 0.

#include <iostream>
#include <vector>

int main()
{
        std::vector<int> v = { 1, 2, 3, 4, 5 };

        try
        {
                for (int i = 0; i <= v.size() + 1; ++i)
                {
                        std::cout << "v[" << i << "] = " << v[i] << std::endl;
                }
        }
        catch (std::out_of_range)
        {
                std::cerr << "Oops! Range Error!" << '\n';
                return 1;
        }
        catch (...)
        {
                std::cerr << "Exception: something went wrong!" << '\n';
                return 2;
        }
}

Compiler is apple clang and c++ standard is c++14.

This is the output. It seems like I am missing something very trivial.

v[0] = 1
v[1] = 2
v[2] = 3
v[3] = 4
v[4] = 5
v[5] = 0
v[6] = 0
Morpheus
  • 3,285
  • 4
  • 27
  • 57

1 Answers1

4

You can't get an out-of-range error because operator[]() is just a memory offset. It doesn't throw. If you want to catch an exception, use the member function at() instead.

sweenish
  • 4,793
  • 3
  • 12
  • 23
  • Since it's **Undefined Behavior**, `operator[]` is in fact allowed to throw on range errors. On Windows, this can happen when the OS itself throws (Structured Exception Handling, similar but not identical to C++ exceptions). Relevant because `catch(...)` can catch those SEH exceptions. – MSalters Apr 08 '21 at 15:59
  • 1
    `catch(...)` doesn't catch SEH unless you are crazy (and set the relevant compiler option) / or have a _very_ old codebase which has it set. Its not been recommended or default behaviour for a long time to have that set. (`/EHa` is the compiler option you really dont want) – Mike Vine Apr 08 '21 at 16:02