How To Work With Db4o Exceptions

Appropriate exception handling will help you to create easy to support systems, saving your time and efforts in the future. The following hints identify important places for exception handling.

  1. Opening a database file can throw a DatabaseFileLockedException:
  2. ExceptionExample.java: openDatabase
    01private static ObjectContainer openDatabase(){ 02 ObjectContainer container = null; 03 try { 04 container = Db4o.openFile(DB4O_FILE_NAME); 05 } catch(DatabaseFileLockedException ex) { 06 // System.out.println(ex.getMessage()); 07 // ask the user for a new filename, print 08 // or log the exception message 09 // and close the application, 10 // find and fix the reason 11 // and try again 12 } 13 return container; 14 }
  3. Opening a client connection can throw IOException:
  4. ExceptionExample.java: openClient
    01private static ObjectContainer openClient(){ 02 ObjectContainer container = null; 03 try { 04 container = Db4o.openClient("host", 0xdb40, "user", "password"); 05 } catch(Db4oIOException ex) { 06 //System.out.println(ex.getMessage()); 07 // ask the user for new connection details, print 08 // or log the exception message 09 // and close the application, 10 // find and fix the reason 11 // and try again 12 } catch (OldFormatException ex) { 13 // see above 14 } catch (InvalidPasswordException ex) { 15 // see above 16 } 17 return container; 18 }
  5. Working with db4o and committing a transaction can throw various exceptions; the best practice is to surround your db4o interaction with try-catch block.
  6. ExceptionExample.java: work
    01private static void work(){ 02 ObjectContainer container = openDatabase(); 03 try { 04 // do some work with db4o 05 container.commit(); 06 } catch (Db4oException ex){ 07 // handle exception .... 08 } catch (RuntimeException ex){ 09 // handle exception .... 10 } finally { 11 container.close(); 12 } 13 }