不要依赖代码中的异常

因为异常大大地降低性能,所以您不应该将它们用作控制正常程序流程的方式。如果有可能检测到代码中可能导致异常的状态,请执行这种操作。不要在处理该状态之前捕获异常本身。常见的方案包括:检查 null,分配给将分析为数字值的 String 一个值,或在应用数学运算前检查特定值。下面的示例演示可能导致异常的代码以及测试是否存在某种状态的代码。两者产生相同的结果。
[C#]
// Consider changing this...
try {
result = 100 / num;
}
catch (Exception e) {
result = 0;
}

// ...to this.
if (num != 0)
result = 100 / num;
else
result = 0;
[Visual Basic]
' Consider changing this...
Try
result = 100 / num
Catch (e As Exception)
result = 0
End Try

// ...to this.
If Not (num = 0)
result = 100 / num
Else
result = 0
End If

posted @ 2004-10-25 00:13  leonardleonard  阅读(112)  评论(0编辑  收藏  举报