【问题标题】:I keep getting an exception even though the code is within a try/catch block [closed]即使代码在 try/catch 块中,我也会不断收到异常 [关闭]
【发布时间】:2017-12-23 23:24:30
【问题描述】:

如果给定的用户输入无效,我编写了一些遇到异常的代码,因此我将它放在 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&amp;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 或其使用的编译器的问题吗?

【问题讨论】:

  • 元素 3 不是您的向量的成员。请改用 2。
  • 计算机系统有不同类型的异常。你只能捕获那些从 C++ 本身抛出的,而不是那些由软件、操作系统或硬件错误引起的。像这样的崩溃你需要learn how to debug your programs
  • 至于您的崩溃背后的原因,您应该回到您的beginners books 并查看它们。
  • 我知道崩溃背后的原因,这是导致超出范围异常的示例代码,以展示如何未捕获异常,如我的帖子“异常本身很清楚,位置“3”并不存在,它会自然而然地抛出异常,但它在 try/catch 块内,所以它应该被捕获,但它没有。”
  • 不,使用operator[]不会使用标准 C++ 引发异常。 Visual C++ 运行时库可能会在调试版本中执行此操作,但这是一个非标准扩展。当抛出异常时,它也可能会抛出一个对话框。如果您让程序继续运行,catch 可能会捕获它。 Visual C++ 有时有点奇怪。

标签: c++ exception visual-c++


【解决方案1】:

如果你想让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';
}

【讨论】:

    【解决方案2】:

    这也不例外。那是调试断言失败。

    如果你想要一个异常,你需要使用向量的 at(index) 函数而不是数组下标运算符。

    【讨论】:

      【解决方案3】:

      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/

      查看底部的异常安全性。

      【讨论】:

        猜你喜欢
        • 2014-08-28
        • 2017-01-30
        • 1970-01-01
        • 2022-11-30
        • 2021-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-11
        相关资源
        最近更新 更多