Exception handlers should preserve the original exception : Either log or rethrow this exception

KSK picture KSK · Aug 4, 2015 · Viewed 7.6k times · Source

This is my method, when I try to analyze my code by sonarQube am getting this error:

Exception handlers should preserve the original exception : Either log or rethrow this exception.

Why am getting this error, should I not catch the exception like my method?

my method :

for (String QT : Q_T) {

                try {
                        // some logic 
                    }

                } catch (JsonParseException e) {                    
                    LOG.log(Level.SEVERE, e.toString());
                } catch (JsonMappingException e) {
                    LOG.log(Level.SEVERE, e.toString());
                } catch (IOException e) {
                    LOG.log(Level.SEVERE, e.toString());
                }
                catch (Exception e) {
                    LOG.log(Level.SEVERE, e.toString());
                }
            }
        }

Answer

carcaret picture carcaret · Aug 4, 2015

I believe what it's trying to tell you is to log the Exception as it is, not the toString() version, like here, also adding some 'context' or information to the log

for (String QT : Q_T) {
        try {
            // some logic 
        } catch (JsonParseException e) {                    
            LOG.log(Level.SEVERE, "context", e);
        } catch (JsonMappingException e) {
            LOG.log(Level.SEVERE, "context", e);
        } catch (IOException e) {
            LOG.log(Level.SEVERE, "context", e);
        } catch (Exception e) {
            LOG.log(Level.SEVERE, "context", e);
        }
}