How can you find the cause of a SQL exception?

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)
This allows you to discover that perhaps an IOException caused the SQLException. This changes the earlier code snippet a little bit to check for causes, and not just loop through all the SQL exceptions:

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();      
    }
  }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact