以下是看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;
}