Example of processing SQLExceptions

A single error can generate more than one SQLException. Usually, but not always, a call to the printStackTrace method displays all these exceptions.

To ensure that all exceptions are displayed, use a loop and the getNextException method to process all SQLExceptions in the chain. In many cases, the second exception in the chain is the pertinent one.

The following is an example:

        ...
    } catch (Throwable e) {
        System.out.println("exception thrown:");
        errorPrint(e);
    }
    ...
}

static void errorPrint(Throwable e) {
    if (e instanceof SQLException) 
        SQLExceptionPrint((SQLException)e);
    else
        System.out.println("A non-SQL error: " + e.toString());
}

static void SQLExceptionPrint(SQLException sqle) {
    while (sqle != null) {
        System.out.println("\n---SQLException Caught---\n");
        System.out.println("SQLState:   " + (sqle).getSQLState());
        System.out.println("Severity: " + (sqle).getErrorCode());
        System.out.println("Message:  " + (sqle).getMessage()); 
        sqle.printStackTrace();  
        sqle = sqle.getNextException();
    }
}

The SQLException may wrap another, triggering exception, such as an IOException. To inspect this additional, wrapped error, call the SQLException's getCause method.

See also "Derby exception messages and SQL states" in the Derby Reference Manual.