Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I keep getting an exception even though the code is within a try/catch block [closed]

I wrote some code that encounters an exception if the given user input is invalid so I put it in a try/catch block yet it still threw an exception. The code itself is quite long so here's a simplified version of the code that also encounters the exception. The exception itself is clear, the position "3" doesn't exist so naturally it would throw an exception, but it's inside of a try/catch block so it should get caught, but it doesn't.

int main() {
    try
    {
        vector<string> test = vector<string>{ "a","b","c" };
        string value = test[3];
    }
    catch (...)
    {

    }
}

Running this code just results in the following exception regardless of whether or not it's in a try/catch block.

Exception

I also tried specifying the exception (const out_of_range&e) but that didn't help either. It just caused the exact same exception.

int main() {
    try
    {
        vector<string> test = vector<string>{ "a","b","c" };
        string value = test[3];
    }
    catch (const out_of_range&e)
    {

    }
}

I'm using Visual Studio, could this be an issue with the IDE or the compiler it uses?

like image 661
Shayna Avatar asked Dec 23 '17 23:12

Shayna


1 Answers

If you want std::vector to throw an std::out_of_range exception, you need to use the .at() method. The operator[] does not throw an exception.

For example, you can do something like this:

std::vector<int> myvector(10);
try {
    myvector.at(20)=100;      // vector::at throws an out-of-range
}
catch (const std::out_of_range& e) {
    std::cerr << "Out of Range error: " << e.what() << '\n';
}
like image 146
Justin Randall Avatar answered Sep 30 '22 18:09

Justin Randall