I have following code using hibernate to throw a custom exception on error and I also want to close the session in this case, since the exception won’t be catched unless received on the client machine.
public <T> T get(final Session session, final String queryName) throws RemoteException
{
final Query query = // query using given session ...
try
{
return (T) query.uniqueResult();
}
catch (final HibernateException e)
{
SessionManager.logger.log(Level.SEVERE, "Could not retrieve Data", e);
this.closeSession(session);
throw new RemoteException("Could not retrieve Data");
}
}
Now I have a helper method which closes the session and throws a given exception:
public void closeSessionAndThrow(final Session session, final RemoteException remoteException)
throws RemoteException
{
this.closeSession(session);
throw remoteException;
}
Now I thought I could simplify my above code using:
public <T> T get(final Session session, final String queryName) throws RemoteException
{
final Query query = // query using given session ...
try
{
return (T) query.uniqueResult();
}
catch (final HibernateException e)
{
SessionManager.logger.log(Level.SEVERE, "Could not retrieve Data", e);
this.closeSessionAndThrow(session, new RemoteException("Could not retrieve Data"));
}
}
Now I need to add a return null; statement after the catch. Why?
Change the declaration of
closeSessionAndThrowto returnRemoteExceptionand then “throw” the return result of calling it in your client code.This tricks the compiler into thinking it will always throw whatever exception is returned from
closeSessionAndThrow. Since the helper method throws that exception itself, this secondthrownever comes into play. While you could return the exception from the helper, this invites error when someone forgets to addthrowbefore the call.