Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to re-throwing exception in catch block?

Tags:

java

exception

Does it make sense to throw exception from catch block just to log the message so that we are sure that what is causing the exception?

Code

  public void saveLogs(Logs logs) throws RemoteException
  {
        try
        {
            LogsOps.saveLogs(logs);
        }
        catch (RemoteException e)
        {
            log.info("RemoteException is thrown while trying to save logs ", e);
            throw new RemoteException("RemoteException caused while trying to save", e);
        }
    }

In response to one of the comments below that this method would throw StackOverFlow Exception, here the actual implementation of log.info which just displays those errors.

     /** Log the message and the exception with a level of INFO.
     * @param message - The message text.
     * @param t - An exception to display.
     */
    public void info(Object message, Throwable t)
    {
        String nullSafeMessage = (message != null) ? message.toString() : t.getClass().getSimpleName();
        log.info(nullSafeMessage, t);
    }

So there never would be Stackoverflow exception thrown.

like image 861
Rachel Avatar asked Dec 11 '22 19:12

Rachel


1 Answers

It depends on what's going to catch the exception higher up. If nothing else is going to log the message, then sure, it makes sense - although I'd probably rethrow the original exception instead of creating a new one:

catch (RemoteException e)
{
    log.info("RemoteException is thrown while trying to save logs ", e);
    throw e;
}

Ideally, though, you'd have a single catch block higher up the stack, which would log appropriately - if you're just logging the exception, that can get all the information anyway.

It may make sense to catch/log/rethrow when you want to log information which isn't present in the exception, such as parameter values.

like image 137
Jon Skeet Avatar answered Dec 29 '22 01:12

Jon Skeet