Logging and throwing exceptions

I was getting tired of remembering to have to log my exceptions and I wanted something to do it for me. I remembered something about generics and exceptions. This is what I came up with:

/**
* <p>A convenience method for
* {@link org.apache.log4j.Logger#error(java.lang.Object, java.lang.Exception) logging}
* and throwing the specified {@link java.lang.Exception}.</p>
*
* <p>Example usage:</p>
*
* <pre>
private void someMethod()
throws SomeException
{
...
LogException.logThrow(log, new SomeException("This will be logged and thrown."));
...
}
* <pre>
*
* @param  log the <code>Logger</code> to which the exception is logged.
* @param  exception the <code>Exception</code> to be logged and <code>throw</code>n
* @throws E the specified exception
*/
public static <E extends Exception> void logThrow(final Logger log,
final E exception)
throws E
{
log.error(exception, exception);
throw exception;
}

The only obvious problem with this technique is that the compiler doesn’t know the method never returns normally. So in a case such as:

public int returnInt()
throws SomeException
{
final int value;
try
{
value = ....
} catch(final OtherException e)
{
LogException.logThrow(log, e);
}
return value;
}

the compiler will complain that value may not have been initialized. Oh well. I can dream can’t I?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s