C++里try,catch,throw的用法

#include<iostream>
#include 
<string>
using namespace std;
class Person
{
private:
 
int age;
 
string name;
public:
 
void setAge(int);
 
void setName(string);
};
class Error
{
public:
    
virtual void show()=0;
};
class nameError:public Error
{
public:
 
void show()
 {
   cout
<<"name is error"<<endl;
 }
 
};
class ageError:public Error
{
public:
 
void show()
 {
   cout
<<"age is error"<<endl;
 }
};
void Person::setAge(int a)
{
 ageError ag;
 
if(a<0||a>100)
  
throw ag;
 
this->age=a;
}
void Person::setName(string str)
{
 nameError ne;
 
if(str=="exit")
  
throw ne;
 
this->name=str;
}

int main(void)
{
  Person p;
 
try
 {
  p.setAge(
0);
  p.setName(
"exit");
 }
 
catch(Error &er)
 {
   er.show();
 }
 cout
<<"hello world"<<endl;
 
return 0;
}

posted on 2011-07-07 16:46 Smart Pointer 阅读(1859) 评论(1)  编辑 收藏 引用

评论

# re: C++里try,catch,throw的用法 2011-12-12 15:54 sudo

不错哟  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2011年7月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

常用链接

留言簿

随笔档案

收藏夹

搜索

最新评论

阅读排行榜

评论排行榜