<p style=line-height: 150%> when used to best advantage, exceptions can improve a programs readability, reliability and maintainability. when used improperly, they can have the opposite effect. playing basketball也一样,漂亮的假动作的确可以帅呆了我,但用得不合理则只能说是花哨而不实用了。
<p style=line-height: 150%> exception可分为三类,checked exceptions, runtime exceptions和errors。 比如,盖帽时可能产生打手等exceptions,但这不会导致比赛就此不能进行。可以通过罚球来go on. 只是你的这次盖帽因犯规而无效,即不能得到你盖帽数增一的结果。这类exception称之为checked exception. 而有时比赛过程中,可能同于球员比现实在是糟糕,而导致观众闹事(晕),比如向现场砸瓶子和水果,从而导致比赛意外中断。比赛能不能go on. 你也不能确定。这样便产生了一个runtime exception. 还有一些情况,比如比赛时,电子记分牌突然产生一个exception.74分变成了47分,这时你也只好叹于无奈,因为这是一个error. 由此看来,checked exceptions是可以恢复的,即可恢复条件下应该用checked exceptions,而后两种exceptions neednt甚至shouldnt be catch. 其中runtime exceptions的出现意味着你的程序本身有问题,你可以通过改进球队的战术来解决。而errors是james gosling的问题,不关你的事。<p style=line-height: 150%> exceptions很有用,但很多情况的exceptions是unnecessary的。 比如下面一个程序: while(没有防守){ try{ 投篮(); }catch(距离太远exception e){ system.out.println("距离远于10米,我可不想三不粘"); } } 这个程序可以正常运行,但如果kobe在后场无人盯防时运球,却不得不停地抛出"距离太远exception",这还真够难为他的。改一下: while(没有防守){ if(距离<5){ 跳投(); } } 这回kobe只要睁着眼,一瞧篮框距离不远,便可起跳了。<p dir=ltr style="margin-right: 0px"> 另外,一方法产生exception后,不应该改变调用该方法对象的状态。如下这个程序就犯了这个毛病: public void 盖帽(){ 盖帽次数++; if(打手) throw new 打手exception(); } 这样一来,一场比赛得三双就容易了很多,呵呵。改成: public void 盖帽(){ if(打手) throw new 打手exception(); 盖帽次数++; } 就行了。这个问题看似easy,却也是最容易犯错的地方。<p style=line-height: 150%> 最后还有一个问题,也是一个最普遍和最严重的问题,那就是:exception没描述清楚.(地球人都知道啊^^) <span lang=en-us style="font-size: 11pt; font-family: times new roman; mso-fareast-font-family: 宋体; mso-font-kerning: 1.0pt; mso-ansi-language: en-us; mso-fareast-language: zh-cn; mso-bidi-language: ar-sa">ignoring </span>an exception is analogous to ignoring a fire alarm--and turning it off so no one else gets a chance to see if theres a real fire. 犯规时,一个裁判得如此描述:a队6号打手犯规,犯规次数累计共3次,并由b队罚球2次。否则,只闻一声哨响,双方球员争嚷,围住一球狂强,拳打脚踢真爽......<p style=line-height: 150%>(责任编辑:zxwq)