Reputation: 437
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:
javax.persistence.PersistenceException
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?
Upvotes: 1
Views: 692
Reputation: 1004
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.
Upvotes: 0
Reputation: 20323
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
.
Upvotes: 1
Reputation: 1793
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!
Upvotes: 2