C++的throw方法怎么用呢?

来源:百度知道 编辑:UC知道 时间:2024/05/14 03:04:02
class Stack3
{
public:
class Underflow{ }; // used as exception
virtual void push(char c) = 0;
virtual char pop() = 0;
};
class Underflow
{
public:
Underflow(){ cout<<"underflow"<<endl;}
};
class Stack:public Stack3
{
public:
void push(char c)
{
throw Overflow();
}
char pop()
{
return 'a';
}
};
int main()
{
Stack st;
st.push('1');

}
//怎么有错呢?该怎么用呢?

找了一个范文,你看看,应该比较好懂。

#include<iostream>
#include <string>
using namespace std;
class Person
{
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.set