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 ...
Get Java Enterprise in a Nutshell, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.