在 c++ 中尝试捕获时没有输出
No output while doing try catch in c++
我正在尝试捕获错误的分配错误。当输入长度的顺序是 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`
}
没有捕获异常可能归结为
您的
int
值比您想象的要小(可能是一些未定义的环绕行为(,并且由于分配成功,因此不会引发异常。
分配是惰性的,因为内存在您实际使用它之前不会分配。
如果
std::bad_alloc
作为匿名临时抛出,那么它将不会在您的捕获地点被捕获。(除非你顽皮的编译器允许非const
引用绑定到匿名临时,有些作为扩展(。改为写catch (const std::bad_alloc&)
,它将被捕获在那里。
整数类型 int 的最大长度为 2.147.483.647 。您确定您实际上使用了更高的数字来测试它吗?
- 您正在传递具有限制的整数变量。 短型变量的最小值:–32768 短类型变量的最大值:32767
- 您将从代码中得到的错误是 std::length_error
- 要动态引发错误的分配错误,您可以尝试大小不正确的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
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 输出没有重复元素的动态数组(收缩数组)C++
- 如何根据单词在文本中出现的概率输出单词