C ++函数未捕获向量下标超出范围的执行

cli*_*cli 1 c++ exception outofrangeexception c++14

我试图在字符“:”上拆分一个字符串,然后查看索引 2 是否存在。我的分割字符串函数工作得很好,因为我已经使用它很长一段时间了,但是在尝试尝试{} catch()之后,它没有捕获执行,而是在我的屏幕上显示调试错误。

    std::vector<std::string> index = split_string(random_stringgg);

    std::cout << index[1] << std::endl;

    try {
        std::string test = index[2];   
    }
    catch (...) {
        std::cout << "error occured" << std::endl;
        return false;
    }
    std::cout << "no error";
Run Code Online (Sandbox Code Playgroud)

据我所知,这应该尝试找到向量“索引”的第二个索引,然后捕获执行(如果没有/无法找到它)。然而,这对我不起作用,即使在添加 try/catch 之后,它也会抛出“向量下标超出范围”。我的问题是为什么它没有捕获并仍然显示错误?

Rem*_*eau 5

std::vector::operator[]不执行任何边界检查,因此如果传入无效索引,也不会出现throw任何异常。访问越界索引operator[]未定义的行为(如果无效索引导致访问无效内存,操作系统可能会引发自己的异常,但您不能使用它catch来处理操作系统错误,除非您的编译器实现了非标准扩展以catch允许这样做)。

如果您希望引发异常,std::vector::at()请执行边界检查。如果传入无效索引,则会抛出throw异常。std::out_of_range

try {
    std::string test = index.at(2);
}
catch (const std::exception &e) {
    std::cout << "error occured: " << e.what() << std::endl;
    return false;
}
Run Code Online (Sandbox Code Playgroud)