看板java
标 题Re: [问题] 写程式style的问题(有关exception)
发信站反地球联邦组织 (Sat May 27 13:45:57 2006)
转信站ptt!ctu-reader!Spring!news.nctu!feeder.seed.net.tw!news.seed.net.tw!AE
※ 引述《[email protected]》之铭言:
> 请问在写Java程式时,
> 好的 style 应该是 "事先预防 exception",
> 还是 "事後再处理 exception"?
> 例如:
> // 事先预防 exception
> public static main(String[] args) {
> if (args.length != 1) {
> System.out.println("Usage: .......");
> return;
> }
> System.out.println("hello," + args[0]);
> }
> // 事後处理 excpetion
> public static main(String[] args) {
> try {
> System.out.println("hello," + args[0]);
> } catch (ArrayIndexOutOfBoundsException e)
> System.out.println("Usage: ........");
> }
> }
> 请问大家在写程式时, 是比较偏好哪一种?
> 理由又是什麽? 谢谢!
说文解字: Exception 叫做例外
既然你知道args[0]有可能出错就是"意料之中的事"
所以请不要把他当"意外状况"去处理
拦截exception的代价不算小
但是也不是在"每一个"method接收args时都要去验证是否正确
会做太多次无谓的判断
--
◤◥ Or
igin:
幽谷˙反地球联邦组织 aeug.twbbs.org
◣◢ A
uthor:
GP03 从
ip135.puli21.ncnu.edu.tw 发表