3.10 Exception Handling


All the examples so far have ignored the possibility of exceptions. JDO defines a set of exceptions that can be thrown by the JDO implementation. All JDO exceptions are declared as runtime exceptions because they can be thrown at anytime , not just when calling JDO methods . As an example, navigating from one instance to another may result in an exception if there is a problem with accessing the datastore when retrieving the fields of an instance.

JDO classifies exceptions broadly into fatal or non-fatal exceptions. Non-fatal exceptions indicate that an operation failed but can be retried, whereas fatal exceptions indicate that the only recourse is to start again. Beyond this, there are user exceptions (fatal or non-fatal), which indicate user error; datastore exceptions (fatal or non-fatal), which indicate a datastore error; an internal exception (fatal), which indicates a problem with the JDO implementation; and an unsupported feature exception (non-fatal), which indicates that the JDO implementation doesn't support a particular feature.

An application should ensure that it handles all exceptions correctly, not just JDO exceptions. In particular, if connection pooling is being used, an application should ensure that a PersistenceManager instance is closed properly even if an exception is thrown. The following code snippet taken from CreateWithExceptionsExample.java shows how to use a try/final block to catch any exception and ensure that the PersistenceManager instance is closed:

 
 PersistenceManager pm = null; try {   pm = pmf.getPersistenceManager();   Transaction tx = pm.currentTransaction();   tx.begin();   Author author = new Author("Keiron McCammon");   pm.makePersistent(author);   tx.commit();   pm.close(); } finally {   if (pm != null && !pm.isClosed()) {     if (pm.currentTransaction().isActive()) {       pm.currentTransaction().rollback();     }     pm.close();   } } 

In this simple example, it really doesn't matter whether the transaction is rolled back or the PersistenceManager is closed because it exits immediately thereafter anyway.



Core Java Data Objects
Core Java Data Objects
ISBN: 0131407317
EAN: 2147483647
Year: 2003
Pages: 146

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net