Search code examples
javaexceptionanti-patterns

Are try/catch for every single statement that throws an exception considered an anti-pattern?


I am currently reviewing a colleagues Java code, and I see a lot of cases where every single statement that may throw an exception being encapsulated in its own try/catch. Where the catch block all perform the same operation (which operation is not relevant for my question).

To me this seems like a code smell, and I do remember reading about it being a common anti-pattern. However I cannot find any references on this.

So are try/catch for every single statement that throws and exception considered an anti-pattern, and what are the argument supporting this?


Constructed example: (Does not relate to the original problem, so please don't mind other problems with this example, as it is just constructed to illustrate what I mean.)

public int foo()
{
    int x, y = 7;

    try
    {
        x = bar(y);
    }
    catch(SomeException e)
    {
        return 0;
    }

    try
    {
        y = baz(x,y);
    }
    catch(SomeOtherException e)
    {
        return 0;
    }

    /* etc. */

    return y;
}

(Assume that it is appropriate to catch both exceptions here, i.e. we know what do with them, and the appropriate thing is to return 0 in both cases.)


Solution

  • I can't serve you with an authoritative source, but these are fundamental tenets of exception handling:

    • exceptions should be caught at the point where one can properly handle them, and
    • you must not swallow exceptions - there should always be (at least) a trace of an exception thrown, so the minimum is to log it, so that at least the developers get a chance of noticing that something bad happened. Which leads to the third point:
    • exceptions should only be used to signal exceptional bad events, not to control program flow.

    There are lots of earlier posts on SO dealing with this, for example Best practices for exception management in JAVA or C#.