0

If I can catch a more specific exception do I prevent the clr from doing extra work and benefit performance wise ? So if I know I might get a socket exception but do not care about handling it differently than some other exception is it better to still have the more specific catch ? I am working on the MicroFramework so small improvements in performance and resources are worth asking about.

 catch (System.Net.Sockets.SocketException netEx)
            {

            }

 catch (Exception ex)
            {

            }
Bill Greer
  • 3,046
  • 9
  • 49
  • 80
  • 1
    Performance is directly related to algorithm complexity and related to how much code must be executed. Having two "catch" statements, simple spoken it is like having two IFs instead of a single IF statement. For this case, more MSIL must be generated to handle two possible situations so there will be more code JIT-ed. But I would NOT consider giving up catching specific exceptions!!! It is very important to catch specific exceptions because you can react more acuratelly and can recover easier. – George Lica Aug 07 '15 at 17:26
  • Wrong question on so many levels. – paparazzo Aug 07 '15 at 18:22
  • How is it the wrong question ? I am not asking for design help. I'm not asking for best practices. I am curious if there is a performance difference between a more granular exception catch vs a more general exception catch. – Bill Greer Aug 08 '15 at 02:15
  • I think it’s worth mentioning there is no JIT for the .NET Micro Framework. All MSIL is interpreted – Michael Baker Nov 07 '15 at 20:57

1 Answers1

2

I would not think about this in terms of performance.

From a code correctness perspective: You should almost always catch the most specific exception you can.

When you catch Exception your exception handler will swallow any exception even if you are not prepared to handle it. Imagine an ArgumentNullException is thrown. The catch block would swallow it and cause confusion.

If all you are prepared to handle is a SocketException then just catch that. If it is less performant so be it. Code correctness is not something to sacrifice for such a miniscule performance gain*

* or no performance gain at all - I am almost certain there is zero execution time performance implication at all. I did a benchmark on my computer and the performance is more or less equal. It was not a comprehensive test but it was enough to confirm my instinct. You can run your own benchmark using a technique similar to this one

Alex Booker
  • 10,487
  • 1
  • 24
  • 34