📄 21-8.txt
字号:
/* 范例:21-8 自定义例外类 */
#include <iostream.h>
class DividByZero // 自定义错误处理类
{
public:
DividByZero( const char *message ):ErrorMsg(message){}
// 结构函数
~DividByZero(){} // 析构函数
const string what() // 送出错误信息
{
ErrorMsg = "算数异常,x不能除以0,这是自定义异常类!\n";
return ErrorMsg;
}
private:
string ErrorMsg;
};
void test()
{
try
{
int i, j;
cout << "Please Input Two Numbers,i除以j, i/j: \n";
cin >> i >> j;
// 当读者输入y的数值是0的话将会发生异常,并激活异常处理类
if(j == 0)
{
throw DividByZero("Dividing by Zero!\n");
// 当 y = 0 时把错误信息类DividByZero送出去
}
else
cout << "i/j = " << i/j << endl;
cout << "Good Result!!" << endl;
}
catch(DividByZero f){ cerr << f.what();} // 异常在此做处理
puts("按Enter键继续...");
getchar();
}
int main()
{
test();
}
程序执行结果﹕
Project p21-8.exe raised exception class DividByZero with message 'Exception Object Address: 0x69346A'. Process stopped. Use Step or Run to continue.
Please Input Two Numbers,i除以j, i/j:
5
0
算数异常,x不能除以0,这是自定义异常类!
按Enter键继续...
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -