Take the 2-minute tour ×

Exceptions thrown by Hibernate are unchecked and from what I've read elsewhere it seems that they are not supposed to be caught in code. However, this means that when for example a temporary database error occurs, the thread in which it occurred dies and our application becomes unresponsive. How should it be done?

Example exceptions that occur:

Caused by: org.hibernate.exception.GenericJDBCException: could not insert
Caused by: java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction

This happens when the application has been running for hours or days.

Much of what I've read talks about how to use Hibernate when integrated into Spring or something similar. Thus, each web request starts a new thread and if that thread dies it only affects that one web request. But in the case of a standalone Java application, how should we deal with it?

share|improve this question
Thanks for quick answers. My approach now is to catch the PersistenceException and throw a PersistenceCheckedException (my own class) and then deal with it depending on what is being done. Either ignoring it (if the database insert isn't crucial) or give up on the DB insert (and the client can try again). Does that sound good? –  GreatFire May 23 '12 at 4:16
add comment

3 Answers

up vote 2 down vote accepted

There is nothing wrong with catching a RuntimeException. It being unchecked is just to give you the option not to.

If you have a specific strategy in mind for handling the exception (like trying again, or triggering something else in your app logic), by all means catch it!

share|improve this answer
add comment

Hibernate Exceptions are unchecked as they don't want to force you to catch them, it is up to the design of the application, if you want to handle at DAO or any where else.

If your case you should handle (Catch) PersistenceException and either take corrective measure of inform your user something bad has happened.

As highlighted by other answer on a general note there is no harm in catching RuntimeException and taking corrective measure, also it is generally advised to throw RuntimeException instead of CheckedException.

share|improve this answer
add comment

If you have a stand-alone application, you can still use Spring. At the end of the day, Spring is nothing but a bunch of java-classes that you configure to load and run. At the centre you have an ApplicationContext object, which is just the object-version of the applicationContext.xml-file.

Basically, in your "public static void main(String[] args)" you create an ApplicationContext from your xml file. Note that ApplicationContext is an interface, so you will probably call the constructor of FileSystemXmlApplicationContext(String configLocation).


Check out http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/beans.html and have a closer look at section 3.2.

share|improve this answer
add comment

Your Answer


