异常处理最佳实践

- 检查传入的外部参数

  如果不符合预期,可返回错误或者抛出异常ArgumentException

 

- 在 catch 块中,始终按从最特定到最不特定的顺序对异常排序

try
{
   ...
}
catch(InvalidOperationException ex)
{
   ...
}
catch(Exception ex)
{
   ...
}

 

 

- 永远不要吞掉异常

这比不捕捉异常还要糟糕得多

try
{
   ....
}
catch(Exception e)
{
}

 

- 把代码清理放在finally block中

即使有using, 有时候也要用到finally, 比如如下例子

string ReadTempFile(string FileName)
{
    try
    {
        using (StreamReader sr = new StreamReader(FileName))
        {
            return sr.ReadToEnd();
        }
    }
    finally
    {
        File.Delete(FileName);
    }
}

当然,有条件用using的地方,一定要先用using

 

- 不要抛出新异常

try
{
line a
// Some code that throws an exception } catch (Exception ex) { // some code that handles the exception line b throw ex; }

这段重新抛出异常的代码改变了stackTrace, 使其指向新的抛出点line b, 而不是原来的抛出点line a

正确的做法:

try
{
    // Some code that throws an exception
}
catch (Exception ex)
{
    // some code that handles the exception
    throw;
}

 

- 不要用异常来处理正常的的代码逻辑

例如:

public static void CheckProductExists(int ProductId)
{
    //... search for Product
    if (ProductId == 0) // no record found throw error
    {
        throw (new Exception("Product is  Not found in inventory"));
    }
    else
    {
        Console.WriteLine("Product is available");
    }
}

正确的做法:

public static bool CheckProductExists(int productId)
{
    //... search for Product
    if (productId == 0) // no record found
    {
        return false;
    }
    else
    {
        return true;
    }
}

 

规则是:所选择的方法依赖于预计事件发生的频率。
1. 如果此事件未经常发生(也就是说,如果此事件确实为异常并指示错误(如意外的文件尾)),则使用异常处理。 如果使用异常处理,将在正常条件下执行较少代码。
2. 如果此事件是例行发生的并被视为正常执行的部分,则使用编程方法来检查错误。 当你以编程方式检查错误时,如果发生异常,则会执行更多代码。

- 写异常日志

  使用日志工具记录发生的异常, 但只记录一次足矣。 记录时要使用ex.ToString(). 光输出ex.Message是不够的,远不能满足需要。

posted @ 2016-09-22 21:32  羽扇冠巾  阅读(192)  评论(0)    收藏  举报