I usually layout my Java SE methods like this. Should I try t开发者_如何学Co catch any exceptions for simple reads like this? I can see using catches for any inserts but for this I don't see the need. Just asking for suggestions.
public List<PkgLineStateHistory> findAllStateHistory() {
EntityManager em = getEntityManager();
List<PkgLineStateHistory> list = null;
try {
return em.createNamedQuery("PkgLineStateHistory.findAll").getResultList();
} finally {
em.close();
}
}
For Java SE applications (which is your case), it's a good practice to close the EM, as you probably are managing the EntityManagerFactory by yourself.
In a managed environment, like inside a Java EE container providing the EM, you don't need to close it, as the container is managing it. Sounds trivial, but not always obvious ;-)
You need to let the exceptions bubble up to outside of your transaction boundaries, else your transactions wont roll back (unless you handle your transactions explicitly, which is more work than you need to do).
Also, I dont think just a finally clause actually catches the exception.
FWIW, most webapps I have seen let the exceptions bubble up all the way, and have some generic error handling mechanism that conjures up an appropriate response. Only catch exceptions if you are going to do something with them.
精彩评论