c ++函数未捕获向量下标超出范围异常

c++ function not catching vector subscript out of range execption

我试图在字符“:”上拆分一个字符串,然后查看索引 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";

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

如果 index 包含的元素少于两个,则 index[2] 会调用未定义的行为,这意味着编译器可以为所欲为。具体来说,不需要抛出异常。如果您想要一个例外,请改用 index.at(2),它指定用于执行此操作。

如果你想让它抛出out-of-range异常,你需要使用std::vector::at()而不是std::vector::operator[]。但是,您真的应该检查 std::vectorsize()

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

如果你想抛出异常,std::vector::at() performs bounds checking. It will throw a 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;
}