When a problem occurs, Derby throws a SQLException. If you print the exception message, you may see something like:

How can you get more information?

SQLException supports a chaining model and Derby uses it when multiple exceptions are involved or more context is needed than just the original exception. Typically the actual problem is the last exception in the chain, so displaying the entire chain will make debugging issues much easier. Here's an example of how to walk the chain.

catch (SQLException e) {
    do {
        System.out.println("\n----- SQLException -----");
        System.out.println("  SQLState:   " + e.getSQLState());
        System.out.println("  Error Code: " + e.getErrorCode());
        System.out.println("  Message:    " + e.getMessage());
        e = e.getNextException();
    } while (e != null);
    // for stack dumps, refer to derby.log or add
    //e.printStackTrace(System.out); above
} 

With JDBC 4.0 (Java 6 and later), causes are supported, cf. Lance Andersen's blog on this. The idiom for printing all SQLExceptions and their causes would then look something like this:

catch(SQLException e) {
     do {
        System.out.println("SQLState:" + e.getSQLState());
        System.out.println("Error Code:" + e.getErrorCode());
        System.out.println("Message:" + e.getMessage());
        Throwable t = e.getCause();
        while(t != null) {
            System.out.println("Cause:" + t);
            t = t.getCause();
        }
        e = e.getNextException();
    } while (e != null);
}

While more "correct" for JDBC 4.0, the latter idiom does not currently give extra information in most cases, since Derby often wraps causes in SQLException, to support showing root causes in earlier versions of JDBC. That is, walking the chain via getNextException() would give you causes for exceptions as well as more (distinct) errors, if present. This "redundancy" may change in the future.

JDBC 4.0 also supports walking the exception chain using a for each loop:

catch (SQLException e) {
    for (Throwable t : e) {
        System.out.println("Message: " + t.getMessage());
    }
}

Inspecting derby.log for the stack dump of the error is often also useful in understanding what's going on.

UnwindExceptionChain (last edited 2012-02-28 13:16:23 by KnutAndersHatlen)