Reputation: 69
I'm following an example code from Programming Principles and Practice Using C++ in one of the example for exception it shows this snippet of code
int main()
{
try {
vector<int> v; // a vector of ints
for (int x; cin >> x; )
v.push_back(x); // set values
for (int i = 0; i <= v.size(); ++i) // print values
cout << "v[" << i << "] == " << v[i] << '\n';
}
catch (const out_of_range& e) {
cerr << "Oops! Range error\n";
return 1;
}
catch (...) { // catch all other exceptions
cerr << "Exception: something went wrong\n";
return 2;
}
}
From what I understand it is suppose to catch out_of_range error and output "Oops! Range error". However, the Visual Studio 2019 shows this instead.
can someone explain why it shows me this
Upvotes: 1
Views: 767
Reputation: 29022
Does “try-catch” catches run time error (especially Out of Range error)?
No, in C++ most run time errors lead to Undefined Behavior, not exceptions. Only errors which explicitly throw exceptions can be caught.
std::vector<T>::operator[]
does not specify that it throws an exception when you access out of bounds, it is just Undefined Behavior and anything can happen. It can even appear to work. When I try it here, there isn't any visible error : https://godbolt.org/z/Pcv9Gn8M9
If you want an exception on out of bounds access, std::vector<T>::at()
does throw std::out_of_range
.
For your test you should use v.at(i)
instead of v[i]
. Try it here : https://godbolt.org/z/szKxhjxhx.
Upvotes: 4