以下是看Think in C++而写的测试例子
#include <iostream>
using namespace std;
class MyErr
{
private:
const char* const data;
public:
MyErr(const char* const msg = 0):data(msg){}
void show(){cout << data <<endl;}
};
void foo()
{
int i;
cout << "输入一个大于0小于8的整数:";
cin >> i;
if(i < 0)
throw MyErr("输入不大于0");
else if(i >= 8)
throw MyErr("输入不小于8");
cout << "ok" <<endl;
}
void foo2()
{
foo();
}
int main(int argc, char *argv[])
{
try
{
foo2();
}
catch(MyErr &e)
{
e.show();
}
return 0;
}