c++exceptionc++14outofrangeexception

c++ function not catching vector subscript out of range execption


I am trying to split a string on the char ":" then see if index 2 exists. My split string function works good as ive been using it for quite some time, but after trying to try{} catch() this it doesnt catch the execption and instead displays a debug error on my screen.

    std::vector<std::string> index = split_string(random_stringgg);

    std::cout << index[1] << std::endl;

    try {
        std::string test = index[2];   
    }
    catch (...) {
        std::cout << "error occured" << std::endl;
        return false;
    }
    std::cout << "no error";

To my knowledge, this should try to find the 2nd index of the vector "index" then catch the execption if it doesnt/cant find it. However, this does not work for me and instead just throws a "vector subscript out of range" even after adding the try/catch. My question is why is it not catching and still displaying the error?


Solution

  • std::vector::operator[] does not perform any bounds checking, so it will not throw any exception if an invalid index is passed in. Accessing an index out of bounds with operator[] is undefined behavior (the OS may raise its own exception if the invalid index causes invalid memory to be accessed, but you can't use catch to handle OS errors, unless your compiler implements a non-standard extension for catch to allow that).

    If you want an exception to be thrown, std::vector::at() performs bounds checking. It will throw a std::out_of_range exception if an invalid index is passed in.

    try {
        std::string test = index.at(2);
    }
    catch (const std::exception &e) {
        std::cout << "error occured: " << e.what() << std::endl;
        return false;
    }