How can you find the cause of a SQL exception?
Created Jun 3, 2007
John Zukowski There are three areas where exception handling your JDBC code has improved with the changes in JDBC 4.0. First off, you can use the Java 5 for-each loop to easily iterate through the cause of an exception. Secondly, there are new constructors for SQLException to pass in the underlying reason for the SQLException. And, lastly, there are many new subclasses of SQLException for cleaner handling of exceptions with their own catch clauses.
In order to support the for-each loop, the SQLException class now implements the Iterable<T> interface, where T is Throwable. The internal vector of SQLException objects can be looped through easily in the catch class of your JDBC code:
try {
...
} catch (SQLException sqle) {
for(Throwable t : sqle) {
System.out.println("Throwable: " + t);
}
}
Not only does the class implement Iterable, but there are four new constructors for SQLException, passing in the cause of the underlying SQL exception:
- SQLException(Throwable cause)
- SQLException(String reason, Throwable cause)
- SQLException(String reason, String sqlState, Throwable cause)
- SQLException(String reason, String sqlState, int vendorCode, Throwable cause)
try {
...
} catch (SQLException sqle) {
for(Throwable t : sqle) {
System.out.println("Throwable: " + t);
Throwable cause = t.getCause();
while (cause != null) {
System.out.println(Cause: + cause);
cause = cause.getCause();
}
}
}