Debajyoti Das
Debajyoti Das

Reputation: 2148

Logging an Exceptions in Java?

I am using commons logging in a Java application, and I want to log the exception from the stack trace.

catch( Exception exception ) {
         logger.error( "FailedCreateActivityFunction Exception Occured : " , exception );
         throw new EngineException( getMessage( ERROR_FailedCreateActivityFunction, FunctionName ), exception );
      }

Will this throw the exception twice ? If yes how to fix it ?

Whats the difference between using it as this way using + exception instead of , exception

logger.error( "FailedCreateActivityFunction Exception Occured : " + exception );

Upvotes: 2

Views: 10058

Answers (2)

mleczey
mleczey

Reputation: 513

No it will not throw exception twice. This code will throw only EngineException.

You should avoid logging and throwing exceptions, do only one thing. Log and throw is an antipattern. You can read more about exception handling here: Exception Handling Antipatterns.

Difference between those two ways of executing error method is:

  • in logger.error(String msg, Throwable t) - you pass object, so logging framework has more information, and can show you full stack trace
  • in logger.error(String msg) - you create String, no additional information is passed to logging framework

Upvotes: 5

Andrea Ligios
Andrea Ligios

Reputation: 50281

No, it won't throw it twice.

The first method will print your message AND the exception's stacktrace.

The second method will print only your message AND the exception message (invoking throwable.toString() that returns a short description of the error), without the stacktrace.

Upvotes: 1

Related Questions