Try-catch: is this acceptable practice?

2019-01-25 08:00发布

问题:

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.

回答1:

This is indeed terrible practice. Especially the catching of Exception rather than something specific gives off a horrible smell - even a NullPointerException will 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:

try {
    // code
}
catch (MyInconsequentialException mie) {
   // tune level for this logger in logging config file if this is too spammy
   MY_LOGGER.warning("Caught an inconsequential exception.", mie);
}

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:

try {
   // code
}
catch (SpecificCheckedException sce) {
   // make sure there is exception logging done farther up
   throw new RuntimeException(sce);
}

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 adding throws SpecificCheckedException to the method signature.

As @Tom Hawtin mentioned, new Error(sce) can be used instead of new RuntimeException(sce) in order to circumvent any additional Exception catches 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.



回答2:

Terrible, indeed. Swallowing an exception like this can be dangerous. How will you know if something bad has happened?

I'd feel better if the vendor wrote comments to document and acknowledge it ("We know what we're doing"). I'd feel even better if there was a strategy apparent in the code to deal with the consequences. Wrap it in a RuntimeException and rethrow; set the return value to an appropriate value. Anything!

"All over the place"? Are there multiple try/catch blocks littering the code? Personally, I don't like that idiom. I prefer one per method.

Maybe you should find a new vendor or write your own.



回答3:

    try {
        meshContinuum.enable(MeshingModel);
    } catch (Exception e) {
    }

This looks like unfinished code. If the enable method throws an Exception then it will be caught and swallowed by the code. If it doesn't then it does not make sense to try to catch a non occuring exception.

Check to see the methods and where their signatures are not followed by throws exceptionName, then remove the empty try-catch statements from the places they are called.

You can theoretically put try-catch around any statement. The compiler will not complain about it. It does not make sense though, since this way one may hide real exceptions.

You can see this as a sign of bad code quality. You should probably be prepared to run into problems of different type too.



回答4:

It's not the best:

  • It hides evidence of the exception so debugging is harder

  • It may cause features to fail silently

  • It suggests that the author might actually have wanted to handle the exception but never got around to it

So, there may be cases where this is OK, such as an exception that really is of no consequence (the case that comes to mind is Python's mkdirs, which throws an exception if the directory already exists), but usually, it's not so great.



回答5:

Unfortunately you cannot just remove it, because it the try block throws a checked exception then it will have to be declared in the throws clause of the method. The callers of the method will then have to catch it (but not if the callers also have this catch (Exception e) {} abomination).

As an alternative, consider replacing it with

try {
    meshContinuum.enable(MeshingModel);
} catch (Exception e) {
    throw (e instanceof RuntimeException) ? (RuntimeException) e : new RuntimeException(e);
}

Since RuntimeException (and classes that extend it) are unchecked exceptions they do not need to be declared in the throws clause.



回答6:

What did your contract with the supplier specify? If what they wrote, bad practice and all, meets the spec then they will charge you for a rewrite.

Better to specify a set of tests that will enter many or all of those try-catch blocks and hence fail. If the tests fail you have a better argument to make them fix their terrible code.



回答7:

Horrible idea on the face of it, totally depends on what you're actually calling. Usually it's done out of laziness or habituated bad practices.