i am using hibernate to execute sql statements in spring but to handle exceptions i used hibernate exception and sql exception but i am not able to handle exceptions
if my sql server is not on or not accessable i am not able to catch exception i am getting error
org.hibernate.exception.JDBCConnectionException
here name.save(user);
is hibernate command that executes sql command
how to catch this type of exceptions
i am getting errors
Unreachable catch block for JDBCConnectionException.This exception is never thrown from the try statement body
Unreachable catch block for SQLException. This exception is never thrown from the try statement body
mycode:
try
{
ApplicationContext appContext =
new ClassPathXmlApplicationContext("/config/BeansInfo.xml");
TokenBo tokenBo = (TokenBo)appContext.getBean("TokenBo");
TokenModel token = new TokenModel();
token.setNumber(Number);
token.setID(ID);
}
catch(JDBCConnectionException ex )
{
System.out.println(ex);
}
catch(SQLException e){}
Use JDBCConnectionException for connection related exceptions and ConstraintViolationException for constrain violation. You should use other exceptions as per your requirement. See enter link description here
In Addition to @Tanjim Rahman,
The Code Snippet
In UserDAOImpl.java
Use ConstraintViolationException to catch the duplicate Entry
@Override
public String addUser(User user)
{
Session openSession = sessionFactory.openSession();
String retStr = null;
try
{
openSession.getTransaction().begin();
openSession.persist(user);
openSession.getTransaction().commit();
retStr = "success";
}
catch (ConstraintViolationException e)
{
openSession.getTransaction().rollback();
String[] tmpArr = e.getSQLException().toString().split(":");
String[] anotherTmpArr = null;
if( tmpArr.length > 1)
{
anotherTmpArr = tmpArr[1].split("for key");
}
retStr = anotherTmpArr[0];
}
catch (HibernateException e)
{
retStr = e.getLocalizedMessage();
}
finally
{
openSession.close();
}
return retStr;
}
you may only catch exceptions that are thrown at you directly (at least for checked exceptions...). If you really want to handle this specific error situation in any reasonable way, there is the possibility to catch what is thrown at you and inspect the cause of the exception provided
try {
// some hibernate calls
} catch (GenericJdbcException ge) {
if(ge.getCause() != null && ge.getCause() instanceof SQLException) {
SQLException se = (SQLException)ge.getCause();
if(se.getErrorCode() == -911) {
// your error handling for this case
}else{
throw ge; // do not swallow unhandled exceptions
}
}else{
throw ge // do not swallow unhandled exceptions
}
}
Credit Oracle Community
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.