我试图用C ++创建一个程序,该程序可以捕获并处理bad_alloc异常。
在编写代码时,我没有发现任何错误,但是当我尝试编译此代码时,在Microsoft Visual Studio Community 2017中得到了C2276错误代码和C3876。
错误本身似乎出现在catch {...}代码块中。
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
class CanGoWrong {
public:
CanGoWrong() {
char *pMemory = new char[9999999999];
delete[] pMemory;
}
};
int main()
{
try {
CanGoWrong wrong;
}
catch(std::bad_alloc &e){
cout << "Caught exception: "<< e.what << e << endl;
}
cout << "Still running" << endl;
return 0;
}
代码C3867的错误(“非标准语法,请使用&”),我通过以下方式解决了此问题:
来自
cout << "Caught exception: "<< e.what << e << endl;
收件人:
cout << "Caught exception: "<< &e.what << e << endl;
仍然,错误C2276不会消失。我想使用基本的std :: exception类可以做些事情。
我想了解正确的做法,此代码是我必须遵循并理解的课程示例。