错误处理代码性能

时间:2016-03-31 09:48:16

标签: c# performance error-handling

我目前正在使用Visual Studio 2010,我在try语句的catch块的代码优化方面遇到了一个场景

我想知道使用

是否有任何差异
catch (System.Exception e)
{
//log.Error(e.Message, e);//log specific type of error

if (e is ArgumentNullException)
{
    //do something here
}
else if (e is SqlException)
{
    //do something else
}
else if (e is NullReferenceException)
{
    //do more things
}
else if (e is System.Exception)
{
   //catch everything in site
}

}

而不是做

catch (SqlException s)
{
    //more things
}
catch (NotFiniteNumberException k)
{
    //more errors
}
catch (System.Exception)
{
    //all
}

这个场景是基于我的错误记录,在第一个语句中,我可以在一个地方记录错误并检查其类型,第二个是我到目前为止使用的,但后来我会必须重复记录错误的同一行。

1 个答案:

答案 0 :(得分:0)

在第二种情况下,您也可以仅检查错误类型并调用函数以在Finaly Block中记录错误。 最后一个块将始终在catch块后调用。

 try
 {
 }
 catch (SqlException s)
 {
     //more things
 }
 catch (NotFiniteNumberException k)
 {
     //more errors
 }
 catch (System.Exception)
 {
     //all
 }
 finally
 {
     Call log function here based on condition
 }