即使代码在try / catch块中,我仍然会收到异常[关闭]

问题描述 投票:6回答:3

如果给定的用户输入无效,我写了一些遇到异常的代码,所以我把它放在try / catch块中,但它仍然引发异常。代码本身很长,所以这里是代码的简化版本,也遇到了异常。异常本身很清楚,位置“3”不存在,所以它会抛出一个异常,但它在try / catch块内,所以它应该被捕获,但事实并非如此。

int main() {
    try
    {
        vector<string> test = vector<string>{ "a","b","c" };
        string value = test[3];
    }
    catch (...)
    {

    }
}

运行此代码只会导致以下异常,无论它是否在try / catch块中。

我也试过指定异常(const out_of_range&e),但这也没有帮助。它只是引起了完全相同的异常。

int main() {
    try
    {
        vector<string> test = vector<string>{ "a","b","c" };
        string value = test[3];
    }
    catch (const out_of_range&e)
    {

    }
}

我正在使用Visual Studio,这可能是IDE或它使用的编译器的问题吗?

c++ exception visual-c++
3个回答
11
投票

如果你想让std::vector抛出std::out_of_range异常,你需要使用.at()方法。 operator[]不会抛出异常。

例如,您可以执行以下操作:

std::vector<int> myvector(10);
try {
    myvector.at(20)=100;      // vector::at throws an out-of-range
}
catch (const std::out_of_range& e) {
    std::cerr << "Out of Range error: " << e.what() << '\n';
}

8
投票

这不是一个例外。这是一个调试断言失败。

如果需要异常,则需要在(索引)函数中使用向量而不是数组下标运算符。


1
投票

operator []在向量容器中重载但不是异常安全的(如果失败,行为未定义,例如在上面的帖子中)

您应该使用.at()函数。它是例外安全的。 cplusplus.com参考说:

Strong guarantee: if an exception is thrown, there are no changes in the container.
It throws out_of_range if n is out of bounds.

阅读:http://www.cplusplus.com/reference/vector/vector/operator[]/ http://www.cplusplus.com/reference/vector/vector/at/

查看底部的异常安全性。

© www.soinside.com 2019 - 2024. All rights reserved.