Throwing an exception in a catch block with hibernate before close in finally
So, I want some confirmation on this. I will explain in pseudo code.
public void my开发者_如何学GoFunc() throws Exception{
Session session = Hibernate.getSession();
try{
//do somthing
} catch(Exception ex){
throw ex;
} finally{
session.close();
}
}
Therefore, if a exception is thrown in the try block the session will never be closed. It will have to wait for the pooled connection timeout before it closes, right? If so, is is there a better practice to catching exceptions with hibernate?
The code in the Finally
block is always executed. So, the session will be closed, regardless of whether or not an exception is thrown in the Catch
block. As kem suggested in a comment, you should try single-stepping through this code in the debugger and see the exact behavior for yourself.
As a side note, you should never write throw ex
because that will reset the call stack of the original exception to the point where this throw statement is executed. The result is that you lose relevant information about where the exception actually occurred. Instead, you should just use throw
. Alternatively, you could create a new exception class and set its InnerException
to ex
, but that seems like extra work for nothing unless you need to add additional information to the stack trace.
Of course, the code you've shown above also raises the bigger question of why you're catching the exception in the first place. Once you've rewritten it to simply throw
the exception in the Catch
block, that's the same thing as you not catching the exception in the first place. Instead, why not just omit the Catch
block altogether and settle for just the Try-Finally
pattern?
public void myFunc()
{
Session session = Hibernate.getSession();
try
{
//do something
}
finally
{
session.Close();
}
}
And then once we've established that the code can be altered to implement the Try-Finally
pattern instead, we can go one further. Why not just replace the whole shebang with a using
statement that takes care of disposing the object for you automatically?
精彩评论