64,654
社区成员
发帖
与我相关
我的任务
分享
class A
{
int key;
A(int n):key(n)
{
init();
}
void init()
{
//some code
throw AException();
}
};
A* a = NULL;
a = new A(3);
#include <iostream>
using namespace std;
class A
{
public:
int key;
A(int n):key(n)
{
init();
}
void init()
{
//some code
throw "error!";//构造函数中抛出异常,用于构造失败场景,如果构造函数抛出了异常就不应该使用该对象。
}
};
int main()
{
A* a = NULL;
//如果不处理异常,运行时会有错误
try
{
a = new A(3);
}
catch (...)
{
cout<<"catch exception!"<<endl;
}
a->key = 2;//运行时报错,此时a还是等于NULL
cout<<a->key<<endl;
}