-1

I am currently using Visual Studio 2010 and I have a scenario I am currently facing in terms of code optimization of the catch block of a try statement

I wanted to know if there are any differences in using

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
}

}

as opposed to doing

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

This is scenario is based on logging the error on my part, in the first statement, I can log the error in one place and check its type, the second one is what I have been using so far, but then I would have to repeat the same line of logging the error.

M.S.
  • 4,283
  • 1
  • 19
  • 42
mahlatse
  • 1,322
  • 12
  • 24
  • Thanks, from [More Elegant Exception Handling Than Multiple Catch Blocks?](http://stackoverflow.com/questions/791390/more-elegant-exception-handling-than-multiple-catch-blocks) its seems this is a VB optimization but I wanted to know if it is efficient in C# as well. – mahlatse Mar 31 '16 at 10:23

1 Answers1

0

In Second case also you can check the error type only and call the function to log error in Finaly Block. Finaly block will always be called after catch block.

 try
 {
 }
 catch (SqlException s)
 {
     //more things
 }
 catch (NotFiniteNumberException k)
 {
     //more errors
 }
 catch (System.Exception)
 {
     //all
 }
 finally
 {
     Call log function here based on condition
 }
huseyin tugrul buyukisik
  • 11,469
  • 4
  • 45
  • 97
  • Would I not have to declare an exceptionvariable that I will set to use in the finally block? or is there a way to access the exception from it? – mahlatse Mar 31 '16 at 10:06
  • Yes you will have to. with respect to performance you can use FxCop which can analysis code and give you best way to write code. – Vikas Gupta Mar 31 '16 at 10:47
  • catch( Exception ex ) { if ( ex is FormatException || ex is OverflowException || ex is ArgumentNullException ) { // write to a log, whatever... return; } throw; } – Vikas Gupta Mar 31 '16 at 10:50
  • I am throwing different error codes for different exception, so I cannot use that functionality, and my question was performance wise, which of the two is better. – mahlatse Apr 01 '16 at 05:09