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

后端 未结 5 1769
佛祖请我去吃肉
佛祖请我去吃肉 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:19

    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 get( ... ) throws RemoteException
    {
        try { ... }
        catch (final HibernateException e)
        {
            throw this.closeSessionAndThrow( ... );  // <-- add "throw" here
        }
    }
    

    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.

提交回复
热议问题