?? 21-3.txt
字號:
/* 范例:21-3 try...throw...catch */
#include <iostream.h>
void main(void)
{
int i, j;
cout << "請輸入兩數(i/j): " << endl;
cout << "i = "; cin >> i;
cout << "j = "; cin >> j;
try // 在執行時,try會檢測監控這個程序區塊。
{
if(j == 0) /* 由設計員判斷,如果使用者鍵入j=0的話,會使用下面的throw()
指令丟出異常。 */
throw("i除以j, j不可以是0"); /* 送出異常后,會由下方定義的catch()異常
處理函數接收 */
cout << "i / j = " << i/j << endl;
}
catch(char s[15])
{
cerr << s << endl; // 將錯誤信息輸出到屏幕上。
}
puts("按任意鍵跳出");
getchar();
}
Project p21-3.exe raised exception class char * with message 'Exception Object Address: 0x693436'. Process stopped. Use Step or Run to continue.
(當出現此信息時,再編譯一次)
程序執行結果﹕
請輸入兩數(i/j):
i = 5
j = 0
i除以j, j不可以是0
按任意鍵跳出
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -