我正在尝试使代码抛出length_error异常。我的目标是检测并处理此异常情况。到目前为止,这是我的尝试:
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char * argv[])
{
string buffer("hi");
cout<<buffer.max_size()<<endl;
try {
while(1) {
buffer.append(buffer);
}
}
catch(length_error &l) {
cout<<"Caught length_error exception: "<<l.what()<<endl;
}
catch(exception &e) {
cout<<"Caught exception: "<<e.what()<<endl;
}
return 0;
}
当我运行程序时,我看到字符串的最大大小为18446744073709551599字节。该程序将继续运行,直到所有内存用完为止。然后就安静了。没有异常被抛出。该程序仍在运行,但其CPU使用率从100%降低到0%左右。附加信息:
作业系统:Mac OS 10.8。
编译器:Clang 5.1
内存:16 GB
最佳答案
我相信您的计算机将进入虚拟内存崩溃,这是因为将字符串增加两个字符很多次的内存消耗。
获得此异常的更有效方法是在一开始创建大小为max_size()+1
的字符串。这是修改您的代码以执行此操作的(至少对我而言),它立即引发您期望的异常:
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char * argv[])
{
string buffer("hi");
cout<<buffer.max_size()<<endl;
try {
std::string blah(buffer.max_size()+1, 'X');
}
catch(length_error &l) {
cout<<"Caught length_error exception: "<<l.what()<<endl;
}
catch(exception &e) {
cout<<"Caught exception: "<<e.what()<<endl;
}
return 0;
}
关于c++ - 如何在C++中导致length_error异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63365407/