作者freesamael (烧卖)
站内Programming
标题Re: 例外处理问题之二
时间Fri Sep 14 06:39:36 2007
: 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)