是否“尝试捕获"?捕获运行时错误(尤其是超出范围的错误) [英] Does "try-catch" catches run time error (especially Out of Range error)
问题描述
在以下示例之一中,我正在遵循使用C ++编程原理和实践中的示例代码,该示例显示了此代码段
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;
}
}
据我了解,应该捕获到 out_of_range 错误并输出"糟糕!范围错误" .但是,Visual Studio 2019却显示了这一点.
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
推荐答案
"try-catch"是否捕获运行时错误(尤其是超出范围的错误)?
Does "try-catch" catches run time error (especially Out of Range error)?
否,在C ++中,大多数运行时错误都导致未定义行为,而不是异常.仅可以捕获明确引发异常的错误.
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 []
未指定在您越界访问时抛出异常,这只是未定义的行为,任何事情都可能发生.它甚至似乎可以正常工作.当我在这里尝试时,没有任何可见的错误: https://godbolt.org/z/Pcv9Gn8M9
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
如果您希望访问范围外的异常,则 std :: vector< T> :: at()
会抛出 std :: out_of_range
.
If you want an exception on out of bounds access, std::vector<T>::at()
does throw std::out_of_range
.
为了进行测试,您应该使用 v.at(i)
而不是 v [i]
.在这里尝试: https://godbolt.org/z/szKxhjxhx .
For your test you should use v.at(i)
instead of v[i]
. Try it here : https://godbolt.org/z/szKxhjxhx.
这篇关于是否“尝试捕获"?捕获运行时错误(尤其是超出范围的错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!