代码改变世界

代码重构-异常处理

2012-08-28 16:51  Spring.Guo  阅读(591)  评论(0编辑  收藏  举报

按照产生异常的原因是否明确,来区分异常的处理方式。避免在代码中全部用try-catch 去检测,甚至使用多重try-catch嵌套处理。

异常明确,可以检测。

比如取钱,很显然输入的取钱金额不能大于余额(信用卡不在考虑之列),这种错误是可以检测的,可排除的。

public void Withdraw (decmal amount){

if(amount>_balance){

throw new ArgumentException("amount too large");

}

_balance-=amount;

}

这种程序,参数如果错误,就会抛出异常。所以调用时,做好代码检查就行了,可以不用try-cath去捕获

调用:

public void main()

{

if(account.CanWithdraw(amount)){

    //withdraw money

}

else{

     console.WriteLine("balance not enough");

}

}

又比如:文本框中要求录入数字,完全不需要使用try-catch 去检测

(你是否这样在写?)

public bool checkNumber(string input){

bool isNumber =false;

try{

      int num = int.parse(input);

      isNumber = true;

}

catch(Exception ex){

      console.writeLine(ex.Message);

}

return isNumber;

}

代码改为:

public bool checkNumber(string input){

return Regex.IsMatch(value, @"^[+-]?/d*[.]?/d*$");

}

 

异常不明确,不可检测。

例如:数据库操作,链接数据库查询。如果数据库服务器当机,或者传递的链接字符串参数错误,正常的代码也会查询失败,会抛出链接异常等错误。像这类异常,具有不确定性,不好检查。(使用try-catch,对抛出的错误进行捕获)。

pulic void Connection(string strConn){

try{

     SqlConnection conn = new SqlConection(strConn);

    //...

}

catch(SqlException ex){

      console.writeLine(ex.Message);

}

}

还比如:文件操作,也需要使用try-catch捕获。