构造函数与throw、catch机制的有关问题

构造函数与throw、catch机制的问题
本帖最后由 fengzhr 于 2013-08-15 16:37:36 编辑
#include <iostream>
using namespace std;
class ageError
{
public:
ageError(int i):_age(i){}
int value(){return _age;}
private:
int _age;
};


class man
{
public:
man(int age)
{
try{
if (age<0) throw ageError(age);
_age=age;
}
catch(ageError &ae)
{
cerr << "i cannot handle this!!!";
cerr << "age is " << ae.value() << endl;
}
}
private:
int _age;
};


void main()
try{
man tman=man(-1);
system("pause");
}
catch(ageError &ae)
{
cerr << "age can not be negative!!!";
cerr << "age is " <<ae.value() <<endl;
system("pause");
}


这段程序,执行后类man的构造函数处抛出的异常被构造函数的catch语句接收到,处理了,是正常的。


但是要是将类man的构造函数改为函数try块的形式,代码如下:
#include <iostream>
using namespace std;
class ageError
{
public:
ageError(int i):_age(i){}
int value(){return _age;}
private:
int _age;
};


class man
{
public:
man(int age)

try{
if (age<0) throw ageError(age);
_age=age;
}
catch(ageError &ae)
{
cerr << "i cannot handle this!!!";
cerr << "age is " << ae.value() << endl;
}

private:
int _age;
};


void main()
try{
man *tman=new man(-1);
system("pause");
}
catch(ageError &ae)
{
cerr << "age can not be negative!!!";
cerr << "age is " <<ae.value() <<endl;
system("pause");
}

这段程序的执行结果竟然是构造函数处catch了一次,main函数处又catch了一次!!!望高手解惑!
c++ 构造函数 try catch

------解决方案--------------------