This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
Well, that's confusing then. The JavaDoc for org.hibernate.engine.jdbc.spi.SqlExceptionHelper says:
Helper for handling SQLExceptions in various manners.
If it doesn't get thrown out of InsertRecord(), then the SQLException is being handled inside InsertRecord() or something that it calls. That handler might rethrow a ConstraintViolationException. I don't have Hibernate set up now, so I can't test that. When you say, you see it in the debugger, do you mean an actual debugger stopped at a break point, or are you seeing it in a log file? If it's a break point, then at which line is it?
I can only think of a couple of ways the catch clause at lines 7 - 9 could fail to catch the exception:
1. The exception is thrown from somewhere else other than the try block.
2. There are more than one class named ContraintViolationException, but in different packages, and your imports are set so that you are not catching the type that is being thrown.
Those are pretty much the only possibilities.
Joined: Jul 24, 2011
You could be right Greg, i observed the exception throw before the persistence exception, but how can we handle it ?
I think I understand what's going on. When you said, "in the debugger, it show me persistenceException and the cause is ConstraintViolationException", you mean you saw a stack track (a series of class names and line numbers), and then a "Caused By", and another stack trace. That means the type of the exception is really PersistenceException. It wraps a ConstraintViolationException, but that's just to provide you with more information about where and why the exception occurred. It doesn't affect the program flow in any way. So, since the code in the try block throws a PersistenceException, the catch block must catch a PersistenceException (or one of its superclasses up to Throwable). The latest code posting you made should work.
If PersisitenceException is what's thrown by (I assume) code you can't control, then you have no choice but to catch and handle that. In the handler (i.e., catch block), if you absolutely have to, you can extract the wrapped ConstraintViolationException using the getCause() method, and from there you can proceed exactly as if that was the exception you caught. I don't exactly recommend that, but it is possible.