Java - 使用 catch 块内的方法返回语句和抛出异常?
我有以下代码使用 hibernate 在错误时引发自定义异常,并且在这种情况下我还想关闭会话,因为除非在客户端计算机上接收到异常,否则不会捕获该异常.
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"));
}
}
现在我需要在 catch 之后添加一个 return null;
语句.为什么?
Now I need to add a return null;
statement after the catch. Why?
推荐答案
修改closeSessionAndThrow
的声明,返回RemoteException
,然后抛出"调用它的返回结果在您的客户端代码中.
Change the declaration of closeSessionAndThrow
to return RemoteException
and then "throw" the return result of calling it in your client code.
public RemoteException closeSessionAndThrow( ... ) // <-- add return type here
throws RemoteException { ... }
public <T> T get( ... ) throws RemoteException
{
try { ... }
catch (final HibernateException e)
{
throw this.closeSessionAndThrow( ... ); // <-- add "throw" here
}
}
这会诱使编译器认为它总是抛出从 closeSessionAndThrow
返回的任何异常.由于辅助方法本身会抛出该异常,因此第二个 throw
永远不会发挥作用.虽然您可以从帮助程序返回异常,但当有人忘记在调用之前添加 throw
时,这会引发错误.
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 second throw
never comes into play. While you could return the exception from the helper, this invites error when someone forgets to add throw
before the call.
相关文章