I have a domain model class which has a toString implementation that looks like this:
public String toString() {
try {
return getX() + "\n"
getY() + "\n"
getZ(); //etc.
} catch(Exception e) {
throw new RuntimeException(e);
}
}
The methods getX()
, getY()
and getZ()
are not simple getters, they can perform lookups in the background, generally a lookup to a static map of predefined key-value pairs. Some of them had throws SomeCheckedException
in their signatures.
My impression is that this is bad practice and a "code smell". The fact that toString()
even needs this check is to me a symptom of bad design. But I'm asked by a colleague, what exactly is wrong with catching the generic Exception
in a toString()
, since the caught Exception
is propagated further.
I believe it violates at least the KISS principle, since a simple method like toString()
here is indicated as requiring special exception handling.
So is it code smell to have a catch-all block in a toString()?
Answers I found were either for the general scenario of catching generic Exception
and I agree with most of them, that if you're doing a generic error handling mechanism or a batch then it's expected to work on generic exceptions. This argument was unconvincing in our discussion, so I'm curious of other opinions.