Re: 例外處理問題之二
: try {
: if (denominator == 0) {
: throw 0;
: } else if (denominator < 0) {
: throw " ~~分母<0 這樣是不行的 ";
: } else {
: cout << numerator << "/" << denominator << "=";
: cout << double (numerator)/double(denominator) << endl;
: }
: }
我不太清楚為什麼你要這樣寫,我覺得這樣的 exception 其實意義不大。
因為你已經用 if 敘述式判斷錯誤了,直接頃印出來就好了。
你的程式碼看起來是只要把 try catch 拿掉,throw 改成 cerr 就能達到你的目的 -
印出錯誤且不計算結果。
就我個人的認知上,exception 的好處是
1) 如果沒有處理 exception 的話,程式在出錯的地方會停下來。這避免錯誤被
隱藏。若程式在出錯之後數千行才不正常中斷,那要 debug 很辛苦。
2) 被丟出來的 exception 可以讓呼叫該 function 的人(caller)視情況做後續
處理。
所以若是我想要一個會丟出 exception 的 fraction,我大概會這樣寫:
void fraction::setDenominator(int d)
throw(UnsatisfiedValueException)
{
if (d <= 0)
throw UnsatisfiedValueException();
else
denominator = d;
}
int main()
{
fraction f;
int d;
cin << d;
try {
f.setDenominator(d);
} catch (UnsatisfiedValueException) {
cerr << "The input value is unsatisfied." << endl;
}
....
}
--
Licensed under CC2.5(TW) by-sa, Samael Wang.
http://creativecommons.org/licenses/by-sa/2.5/tw/
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.135.82.153
※ 編輯: freesamael 來自: 220.135.82.153 (09/14 06:42)
討論串 (同標題文章)
完整討論串 (本文為第 7 之 7 篇):
1
2
Programming 近期熱門文章
PTT數位生活區 即時熱門文章