?? 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 + -