Could you hire me? Contact me if you like what I’ve done in this article and think I can create value for your company with my skills.

October 9, 2022 / by Zsolt Soczó

Exception handling mistakes

You have learned that you have to think about exception handling cautiously. For example, do NOT catch too broad exception types like System.Exception.

Here is a real-world example of why it is considered harmful.

Problematic exception handling

I suppose the programmer who wrote this code anticipated bogus XML input and wanted to handle it by that catch block.
There are several problems here.
When the catch branch is activated, the contactInfo local variable remains null, so line 243 will experience NullReferenceException. And so it did. Actually, that’s why I examined the code.
If you use ReSharper, it will flag this kind of bogus code by null flow analysis.
But there is another problem here. The XML loading was successful! Despite this fact, the catch caught an exception. It was a NullReferenceException! Now you see a catch-all exception handler hides a programmer error, hides the fact a null reference was not expected and checked.

The proper solution would catch XmlExeption only. Besides, the programmer has to decide what a bogus XML means and how to proceed. The rest of the method may be pointless to execute in this case.

Moral of the story: catch specific exceptions, and do not be an ignorant person when a tool shows you a potential problem. I have seen this phenomenon in many companies. Resharper or the C# compiler screams that the code potentially blows up or does not do what the programmer intended, but they ignore it. Then the code kicks their ass at runtime. You should know Murphy hates programmers.

Could you hire me? Contact me if you like what I’ve done in this article and think I can create value for your company with my skills.