Java - Return statement and thrown exception using method inside catch block?

后端 未结 5 1838
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-21 15:40

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 receiv

5条回答
  •  没有蜡笔的小新
    2021-01-21 16:01

    While closeSessionAndThrow always throws the remote exception, the compiler doesn't dive into the method to find that out, therefore the compiler only knows that it COULD throw a RemoteException, not that it WILL. I would maybe do something like this:

    public RemoteException closeSessionAndThrow(final Session session, final Exception e, String msg)
    {
        SessionManager.logger.log(Level.SEVERE, msg, e);
        this.closeSession(session);
        return new RemoteException(msg);
    }
    
    public  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)
        {
            throw this.closeSessionAndThrow(session, e, "Could not retrieve Data");
        }
    }
    

提交回复
热议问题