Why is “catch (Exception ex)” a problem?

Let’s consider the code below. In the try block there is a bug (null reference exception). This is then caught in the catch block and logged.

try
{
    string name = null;       
    int length = name.Length; // bug
}
catch (Exception ex) // why is this bad?
{
    // logging...
    Console.WriteLine(ex.Message + ": " + ex.StackTrace);
}

Why is this catch (Exception ex) a problem?

There is a bug in the try block. If the bug is just logged you are unlikely to notice there is a bug. You probably do not read all the logs all the time.

To be able to fix the bug you need to actually notice there is a bug. One way to do this is to let the program crash in case of a bug. Do not hide the bug PuTTY 615-544-5418 , expose it!

Do not catch all exceptions but only catch specific expected exceptions.
Of course do not catch the NullReferenceException as this would again hide the bug.

Leave a Reply

Your email address will not be published. Required fields are marked *