0

I have been trying to run through the standard exceptions and catch them as an exercise.

I am having trouble with catching out_of_range with the following code in visual studio (windows), instead of my code catching the exception, instead I get a Microsoft Visual C++ Runtime libary popup, "debug assertion failed" .

Am I missing a project setting perhaps?

int main() {
    try {
        vector<int> myVector(10);

        myVector[22] = 100;

    }

    catch (const std::out_of_range &exception)
    {
        std::cout << "exception caught: " << exception.what() << std::endl;
    }
}
  • 5
    TL;DR of the dupe: You need to use `at`, not `[]`, if you want an out of bounds exception to be thrown. – NathanOliver Feb 17 '20 at 21:11
  • 2
    `[]` operator does not throw an exception, use `myVector.at(22)` instead. – Tarek Dakhran Feb 17 '20 at 21:11
  • In addition to the above: accessing arrays out of bounds (including, but not limiting, to, accessing vectors out of bounds, with `operator[]`) is undefined behavior, and if you do that, there are no guarantees on the behavior of your code. – Algirdas Preidžius Feb 17 '20 at 21:13
  • Thanks @Tarek Dakhran, tried - myVector.at(22) = 10; got it caught by my catch; Thanks for the Clarification @ Algirdas, so straight to undefined behaviour for the [] operators. – Damien Axe Feb 17 '20 at 21:20

0 Answers0