We have received Java code from a software supplier. It contains a lot of try-catch blocks with nothing in the catch part. They’re all over the place. Example:
try {
spaceBlock.enable(LindsayModel);
} catch (Exception e) {
}
My questions are: Is the above acceptable practice? If so, when? Or should I just go ahead and remove all of these “bogus” try and catch statements?
To me this looks like terrible practice, but I’m not experienced enough in Java to tell for sure. Why catch errors if you’re not going to do anything with them? Seems to me, you would only do that if you were confident that an exception would be of absolutely no consequence and you don’t care if one occurs. However, this is not really the case in our particular application.
EDIT To give some context: We bought a Java-scriptable product from the supplier. Alongside the product, they provided a large proof-of-concept script tailored to our needs. This script came “free of charge” (though we wouldn’t have bought the product if it hadn’t come with the script) and it “works”. But the script is a real pain to build upon, due to many things that even I as a Java novice recognise as awful practice, one instance being this bogus try-catch business.
This is indeed terrible practice. Especially the catching of
Exceptionrather than something specific gives off a horrible smell – even aNullPointerExceptionwill be swallowed. Even if it is assured that a particular thrown exception is of no real consequence, one should always log it at the very least:However it is unlikely an exception is completely meaningless in this situation. I recommend researching exactly what exception(s) the application’s code is intending to swallow here, and what they would really mean for the execution.
One important distinction is whether the try/catches are used to swallow checked exceptions. If this is the case, it probably indicates extreme apathy on the programmer’s part – somebody just wanted his/her code to compile. At the least, the code should be amended:
This will rethrow the exception wrapped in an unchecked
RuntimeException, effectively allowing the code to compile. Even this can be considered a bandaid however – best practice for checked exceptions is to handle them on an individual basis, either in the current method or farther up by addingthrows SpecificCheckedExceptionto the method signature.As @Tom Hawtin mentioned,
new Error(sce)can be used instead ofnew RuntimeException(sce)in order to circumvent any additionalExceptioncatches farther up, which makes sense for something that isn’t expected to be thrown.If the try/catch is not being used to swallow checked exceptions, it is equally dangerous and should simply be removed.