Search code examples
c#.netclr.net-micro-framework

Does more specific exception handling improve performance?


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)
            {

            }

Solution

  • 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