C++ string::at() 方法越界异常处理

以下 C++ 代码演示了使用 string::at() 方法访问字符串中越界元素时如何导致 'out_of_range' 异常,并展示了如何使用 try-catch 块优雅地处理此异常:c++#include #include

using namespace std;

int main() { string s = 'Hello';

try { // 尝试访问索引为 5 的元素,这将导致越界访问 s.at(5); } catch (out_of_range &e) { // 捕获 out_of_range 异常并打印错误信息 cerr << e.what() << endl; }

return 0;}

程序输出:

basic_string::at: __n (which is 5) >= this->size() (which is 5)

解释:

  • string::at() 方法用于访问字符串中指定索引处的字符。* 如果提供的索引超出了字符串的有效范围(0 到字符串长度 - 1),则 at() 方法会抛出一个 'out_of_range' 异常。* 在上面的代码中,我们尝试访问 s[5],而字符串 'Hello' 的长度为 5,有效索引范围是 0 到 4。因此,at() 方法抛出一个异常。* try-catch 块用于捕获异常并防止程序崩溃。catch 块捕获 'out_of_range' 异常,并使用 e.what() 打印错误信息。

通过使用 try-catch 块,我们可以有效地处理 'out_of_range' 异常,并提供更有意义的错误消息,从而使程序更加健壮和可靠。

C++ string::at() 方法越界异常处理

原文地址: https://www.cveoy.top/t/topic/k6y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录