O'Reilly logo

Java Enterprise in a Nutshell, Third Edition by William Crawford, Jim Farley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Handling Errors

Any JDBC object that encounters an error serious enough to halt execution throws a SQLException. For example, database connection errors, malformed SQL statements, and insufficient database privileges all throw SQLException objects.

The SQLException class extends the normal java.lang.Exception class and defines an additional method called getNextException(). This allows JDBC classes to chain a series of SQLException objects together. SQLException also defines the getSQLState() and getErrorCode() methods to provide additional information about an error. The value returned by getSQLState() is one of the ANSI-92 SQL state codes ; these codes are listed in Appendix D. getErrorCode() returns a vendor-specific error code.

An extremely conscientious application might have a catch block that looks something like this:

try {
 // Actual database code
}
catch (SQLException e) {
  while(e != null) {
    System.out.println("\nSQL Exception:");
    System.out.println(e.getMessage());
    System.out.println("ANSI-92 SQL State: " + e.getSQLState());
    System.out.println("Vendor Error Code: " + e.getErrorCode());
    e = e.getNextException();
  }
}

SQL Warnings

JDBC classes also have the option of generating (but not throwing) a SQLWarning exception when something is not quite right, but at the same time not sufficiently serious to warrant halting the entire program. For example, attempting to set a transaction isolation mode that is not supported by the underlying database might generate a warning ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required