SqlConnection conn = new SqlConnection(""); try { conn.Open(); // some operation // some additional operations } catch(Exception ex) { // handle the exception } finally { if (conn != null && conn.State == ConnectionState.Open) conn.Close(); // closing the connection } 尽可能的用校验代码而避免使用异常。如果你知道一个可避免的条件可能会出现,那就让它避免。比如,在执行任何操作以前,检查空值(VB里是Nothing),这样可以避免使用异常以及性能问题。
以下代码:
double result = 0; try { result = firstVal/secondVal; } catch(System.Exception e) { // handling the zero divided exception } 应该替换成:
double result = 0; if(secondVal != null && secondVal > 0) { result = firstVal/secondVal; } else { result = System.Double.NaN; } 不要为没有必要的情况(原文:reasons)抛出异常。再次抛出异常的开销和实例化一个新异常的开销一样的大,同时再次抛出异常使程序调试工作增加难度。比如:
try { // Perform some operations ,in case of throw an exception… } catch (Exception e) { // Try to handle the exception with e throw; } 推荐的处理不同的错误的不同的方法是实现一系列的catch块,这看起来好像没有什么,但可以让你的异常处理从特殊走向普通。比如捕获一个和文件有关的异常明显要比捕获一个FileNotFoundException, DirectoryNotFoundException, SecurityException, IOException, UnauthorizedAccessException甚至最后的基类Exception,好的多。