Programming Practices – Arguments Against Error Suppression

error handlinglanguage-agnosticprogramming practices

I've found a piece of code like this in one of our projects:

    SomeClass QueryServer(string args)
    {
        try
        {
            return SomeClass.Parse(_server.Query(args));
        }
        catch (Exception)
        {
            return null;
        }
    }

As far as I understand, suppressing errors like this is a bad practice, as it destroys useful information from the original server's exception and makes the code continue when it actually should terminate.

When is it appropriate to completely suppress all errors like this?

Best Answer

Imagine code with thousands files using a bunch of libraries. Imagine all of them are coded like this.

Imagine, for example, an update of your server causes one configuration file disappear; and now all you have is a stack trace is a null pointer exception when you try using that class: how would you resolve that? It could take hours, where at least just logging the raw stack trace of the file not found [file path] may enable you to resolve momentarily.

Or even worse: a failure in one off the libraries you use after an update that makes your code crash later on. How can you track this back to the library ?

Even without robust error handling just doing

throw new IllegalStateException("THIS SHOULD NOT HAPPENING")

or

LOGGER.error("[method name]/[arguments] should not be there")

may save you hours of time.

But there are some cases where you might really want to ignore the exception and return null like this (or do nothing). Especially if you integrate with some badly designed legacy code and this exception is expected as a normal case.

In fact when doing this you should just wonder if you really are ignoring the exception or "properly handling" for your needs. If returning null is "properly handling" your exception in that given case, then do it. And add a comment why this is the proper thing to do.

Best practices are things to follow in most of cases, maybe 80%, maybe 99%, but you'll always find one edge case where they don't apply. In that case, leave a comment why you're not following the practice for the others (or even yourself) who will read your code months later.