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.
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?
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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With