Skip Headers

# Exceptions at Commit Time

Previous

Next

TopLink exceptions are instances of `RuntimeException`, which means that methods that throw them do not have to be placed in a `try`-`catch` block.

However, the unit of work `commit` method is one that should be called within a `try`-`catch` block to deal with problems that may arise.

Example: Handling Unit of Work Commit Exceptions shows one way to handle unit of work exceptions:

Handling Unit of Work Commit Exceptions

    UnitOfWork uow = session.acquireUnitOfWork();
    Pet petClone = (Pet)uow.registerObject(newPet);
    petClone.setName("Assume this name is too long for a database constraint");
    // Assume that the name argument violates a length constraint on the database.
    // This will cause a DatabaseException on commit
    try {
        uow.commit();
    } catch (TopLinkException tle) {
        System.out.println("There was an exception: " + tle);
    }

This code produces the following output:

    There was an exception: EXCEPTION [ORACLEAS TOPLINK-6004]: oracle.toplink.exceptions.DatabaseException

See "Database Exceptions (4002 – 4018)" for more information on `DatabaseException`.

If you use optimistic locking, you must catch exceptions at commit time because the exception raised is the indication that there was an optimistic locking problem. Optimistic locking allows all users to access a given object, even if it is currently in use in a transaction or unit of work. When the unit of work attempts to change the object, the database checks to ensure that the object has not changed since it was initially read by the unit of work. If the object has changed, the database raises an exception, and the unit of work rolls back the transaction. For more information, see "Locking and the Unit of Work".

If you are using an external transaction service, exceptions may be thrown long after your `UnitOfWork` code has returned. Using `UnitOfWork` method `writeChanges`, you can catch and handle most exceptions before the external transaction is committed. For more information, see "External Transaction Commit Exceptions".