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.)
I can't serve you with an authoritative source, but these are fundamental tenets of exception handling:
There are lots of earlier posts on SO dealing with this, for example Best practices for exception management in JAVA or C#.