【问题标题】:Error Handling Code Performance [duplicate]错误处理代码性能 [重复]
【发布时间】:2016-07-19 16:43:42
【问题描述】:

我目前正在使用 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
}

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

【问题讨论】:

标签: c# performance error-handling


【解决方案1】:

在第二种情况下,您也可以仅检查错误类型并调用函数在 Finaly Block 中记录错误。 finaly 块总是在 catch 块之后被调用。

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

【讨论】:

  • 我是否不必声明一个我将设置为在 finally 块中使用的异常变量?或者有没有办法从中访问异常?
  • 是的,你必须这样做。在性能方面,您可以使用 FxCop,它可以分析代码并为您提供编写代码的最佳方式。
  • catch( Exception ex ) { if ( ex is FormatException || ex is OverflowException || ex is ArgumentNullException ) { // 写入日志,不管... return; } 扔; }
  • 我为不同的异常抛出了不同的错误代码,所以我不能使用该功能,我的问题是性能方面的问题,两者哪个更好。
猜你喜欢
  • 2017-10-31
  • 2010-09-05
  • 2016-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多