在 c++ 中尝试捕获时没有输出

No output while doing try catch in c++

本文关键字:输出 c++      更新时间:2023-10-16

我正在尝试捕获错误的分配错误。当输入长度的顺序是 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000我不知道为什么它没有被抓住。任何帮助将不胜感激!

# include <vector>
# include <iostream>

using namespace std;
void length(int m)
{
    vector<int> x;
    try
    {
    x.resize(m);
    }
    catch(std::bad_alloc&) 
    {
        cout << "caught bad alloc exception" << std::endl;
    }
}
int main()
{
    int l;
    cout << "Length" ;
    cin >> l ;
    length(l);
    return 0;
}

更新:

当我对输入值进行硬编码时,它会引发异常。我不知道为什么它以这种方式工作。

# include <vector>
# include <iostream>

using namespace std;

void length(int m)
{
    vector<int> x;
    try
    {
    x.resize(m);
    }
    catch(std::bad_alloc&) 
    {
        cout << "caught bad alloc exception" << std::endl;
    }
}
int main()
{
    int m= 100000000000000000000;
    length(m);
    return 0;
}

你应该写

if (!(cin >> l)){
    // I could not read that into `l`
}

没有捕获异常可能归结为

  1. 您的int值比您想象的要小(可能是一些未定义的环绕行为(,并且由于分配成功,因此不会引发异常。

  2. 分配
  3. 惰性的,因为内存在您实际使用它之前不会分配。

  4. 如果std::bad_alloc作为匿名临时抛出,那么它将不会在您的捕获地点被捕获。(除非你顽皮的编译器允许非const引用绑定到匿名临时,有些作为扩展(。改为写catch (const std::bad_alloc&),它将被捕获在那里。

整数类型 int 的最大长度为 2.147.483.647 。您确定您实际上使用了更高的数字来测试它吗?

  1. 您正在传递具有限制的整数变量。 短型变量的最小值:–32768 短类型变量的最大值:32767
  2. 您将从代码中得到的错误是 std::length_error
  3. 要动态引发错误的分配错误,您可以尝试大小不正确的malloc((或尝试以下代码。

#include <iostream>
#include <new>
int main()
{
    try {
        while (true) {
            new int[100000000ul];
        }
    } catch (const std::bad_alloc& e) {
        std::cout << "Allocation failed: " << e.what() << 'n';
    }
}
</i>

不会引发异常,因为进入函数void length(int m)int上限为远小于 vector::max_size() 的最大值。考虑:

void length(int m)
{
    cout << "m is: " << m << " which has a max value: " << numeric_limits<int>::max() <<  endl;
    // ...
}

输出: Length10000000000000000000000 m is: 2147483647 and has a max value: 2147483647