Either log or rethrow this exception

Hesam picture Hesam · Aug 25, 2015 · Viewed 21k times · Source

Possible duplicate of Sonar complaining about logging and rethrowing the exception.

This is my code in a class:

try
    {
        this.processDeepLinkData(data);
    }
    catch (final Exception e)
    {
        // Error while parsing data
        // Nothing we can do
        Logger.error(TAG, "Exception thrown on processDeepLinkData. Msg: " + e.getMessage());
    }

and my Logger class:

    import android.content.Context;
    import android.util.Log;
    import com.crashlytics.android.Crashlytics;

    public final class Logger
    {
        /**
         * Convenience method.
         *
         * @see Logger#log(String, String)
         */
        public static void error(final String tag, final String msg)
        {
            if (Logger.DEBUG)
            {
                Log.e(tag, "" + msg);
            }
            else
            {
                Logger.log(tag, "" + msg);
            }
        }

        private static void log(final String tag, final String msg)
        {
            Crashlytics.log(tag + ": " + msg);
        }
}

Sonar is pointing to catch (final Exception e) and says Either log or rethrow this exception. What do you think?

Answer

benzonico picture benzonico · Aug 25, 2015

If you look at the rule description : https://rules.sonarsource.com/java/RSPEC-1166

And especially the title :

Exception handlers should preserve the original exception

In your case you are only taking care of the message of the exception, thus not preserving the eventual stacktrace (and so the root cause of the failure).

This rule detects that you are not using the caught exception as an entire object in the catch block.

This might not be suitable in your case : either mark the rule as "won't fix" or deactivate it in your quality profile.