【发布时间】: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
}
这是基于我自己记录错误的场景,在第一个语句中,我可以在一个地方记录错误并检查其类型,第二个是我迄今为止一直在使用的,但是我会必须重复记录错误的同一行。
【问题讨论】:
-
谢谢,More Elegant Exception Handling Than Multiple Catch Blocks? 看来这是一个 VB 优化,但我想知道它在 C# 中是否也有效。
标签: c# performance error-handling