Exception is caught when Exception is not thrown
Asked Answered
B

2

8

I have the following code and findbugs complains that "Exception is caught when Exception is not thrown" under dodgy code. I do not understand how to solve this. getPMMLExportable throws a MLPMMLExportException.

public String exportAsPMML(MLModel model) throws MLPmmlExportException {
    Externalizable extModel = model.getModel();

    PMMLExportable pmmlExportableModel = null;

    try {
        pmmlExportableModel = ((PMMLModelContainer) extModel).getPMMLExportable();
    } catch (MLPmmlExportException e) {
       throw new MLPmmlExportException(e);
    }
}
Bauer answered 16/11, 2015 at 6:22 Comment(4)
what's the point of catching the exception? You just throw it again. Just remove the try/catch.Adar
I added it in case I am going to log a message before the exception is thrownBauer
then you should use "throw e"Cnidus
Don't catch-and-throw. This is a well-known code smell, or should I say anti-pattern.Emeraldemerge
C
16

This is a very famous findbug warning,

according to official documentation this kind of warning is generated when

  • Method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block.
  • Sometimes it also is thrown when we use catch(Exception e) to catch all types of exceptions at once, it could mask actual programming problems, so findbugs asks you to catch specific exception, so that run-time exceptions can be thrown which indicate programming problems.

for more understanding(and the solution as well) you can have look at the official documentation.

for your case it seems that statements in try clause do not throw the exception you are handling in catch clause

hope this helps!

Good luck!

Cardioid answered 16/11, 2015 at 6:28 Comment(0)
I
0

If you're trying to catch all exceptions, and want to avoid this issue, you need to break your catching into at least 2 blocks. An easy way to do this is catch runtime exceptions in one block, and all others in another.

Discussed here as well

try {
  // Do stuff here, like process json, which might throw a json processing error
} catch (RuntimeException e) {
  throw new RuntimeException("Couldn't process stuff", e);
} catch (Exception e) {
  throw new RuntimeException("Something failed!", e);
}
Isogloss answered 14/8, 2020 at 17:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.