"try-catch" 是否捕获 运行 时间错误(尤其是超出范围错误)
Does "try-catch" catches run time error (especially Out of Range error)
我正在遵循 Programming Principles and Practice Using C++ 中的示例代码,其中一个异常示例显示了这段代码
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 年显示了这一点。
谁能解释为什么它会显示这个
Does “try-catch” catches run time error (especially Out of Range error)?
不,在 C++ 中大多数 运行 时间错误导致未定义的行为,而不是异常。只能捕获显式抛出异常的错误。
std::vector<T>::operator[]
没有指定当你越界访问时抛出异常,它只是未定义的行为,任何事情都可能发生。它甚至可以看起来有效。当我在这里尝试时,没有任何可见的错误:https://godbolt.org/z/Pcv9Gn8M9
如果您想要越界访问异常,std::vector<T>::at()
会抛出 std::out_of_range
。
对于您的测试,您应该使用 v.at(i)
而不是 v[i]
。在这里试试:https://godbolt.org/z/szKxhjxhx.
我正在遵循 Programming Principles and Practice Using C++ 中的示例代码,其中一个异常示例显示了这段代码
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 年显示了这一点。
谁能解释为什么它会显示这个
Does “try-catch” catches run time error (especially Out of Range error)?
不,在 C++ 中大多数 运行 时间错误导致未定义的行为,而不是异常。只能捕获显式抛出异常的错误。
std::vector<T>::operator[]
没有指定当你越界访问时抛出异常,它只是未定义的行为,任何事情都可能发生。它甚至可以看起来有效。当我在这里尝试时,没有任何可见的错误:https://godbolt.org/z/Pcv9Gn8M9
如果您想要越界访问异常,std::vector<T>::at()
会抛出 std::out_of_range
。
对于您的测试,您应该使用 v.at(i)
而不是 v[i]
。在这里试试:https://godbolt.org/z/szKxhjxhx.