首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

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

2013-08-16 
构造函数与throw、catch机制的问题本帖最后由 fengzhr 于 2013-08-15 16:37:36 编辑#include iostreamusi

构造函数与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
------解决方案--------------------


...别误导楼主,构造函数为什么不能抛异常..当然可以。而且构造函数抛异常一般来说是推荐的。说的是析构函数不能抛异常..别混淆了。

回答楼主的问题,这个确实是会再抛出去的,在C++规范中有规定:
“The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor. [...]”

说白了就是如果class man中的catch最后一条语句执行完后异常会再抛出。也就是说如果最后一行没有执行,就不会抛出了。楼主可以在最后一句打印"age is"之前加个return看看,是不是就不会抛出了。

热点排行