First of all, persist()
is not what will throw the exception. persist()
only marks the object as persistent by attaching it to the persistence context. The actual insert will happen at flush time.
Second, it seems that you want to do that in a loop. All runtime exeptions are irrecoverable and leave the context in an unreliable state. As soon as you get an exception, the current transaction should be rollbacked and you shouldn't keep using the entity manager.
And finally, these two facts and common good practices lead to the solution: you shouldn't rely on exceptions to detect incorrect values. If names should be unique, then you should issue a query to test if the entered names already exist in the table, and only insert once you have validated everything. Of course, you could have a race condition between two concurrent transaction, but this situation won't happen often, and you can thus use a generic "Oops" error message to handle it (or retry the transaction if really necessary).