Вы можете поймать либо общее JDBCException
:
try {
userDao.save(user); //might throw exception
} catch(JDBCException e) {
//Error during hibernate query
}
или вы также можете поймать один из более определенных подклассов JDBCException
, например ConstraintViolationException
или JDBCConnectionException
:
try {
userDao.save(user); //might throw exception
} catch(ConstraintViolationException e) {
//Email Address already exists
} catch(JDBCConnectionException e) {
//Lost the connection
}
и с помощью метода e.getCause()
вы можете извлечь базовый SQLException
и проанализировать его далее:
try {
userDao.save(user); //might throw exception
} catch(JDBCException e) {
SQLException cause = (SQLException) e.getCause();
//evaluate cause and find out what was the problem
System.out.println(cause.getMessage());
}
Который напечатал бы, например: Duplicate entry 'UserTestUsername' for key 'username'