【发布时间】:2012-06-27 06:57:21
【问题描述】:
我有以下代码使用 hibernate 在错误时引发自定义异常,并且在这种情况下我还想关闭会话,因为除非在客户端计算机上接收到异常,否则不会捕获该异常。
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");
}
}
现在我有一个辅助方法可以关闭会话并抛出给定的异常:
public void closeSessionAndThrow(final Session session, final RemoteException remoteException)
throws RemoteException
{
this.closeSession(session);
throw remoteException;
}
现在我想我可以使用以下代码来简化上面的代码:
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"));
}
}
现在我需要在 catch 之后添加一个 return null; 语句。为什么?
【问题讨论】: