我有下面的代碼使用hibernate拋出一個錯誤的自定義異常,我也想在這種情況下關閉會話,因爲除非在客戶端機器上接收到異常將不捕獲。Java - 使用catch塊中的方法返回語句和拋出的異常?
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");
}
}
現在我有一個關閉會話,並拋出一個給定的異常的helper方法:
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;
語句。爲什麼?
感謝您的回答。是的,我忘了該方法不保證拋出異常!,編譯器應該如何知道這一點。 – djmj