Handling SQLExceptions
When JDBC encounters an error during an interaction with a data source, it throws an instance ofSQLExceptionas opposed toException. (A data source in this context represents the database to which aConnectionobject is connected.) TheSQLExceptioninstance contains the following information that can help you determine the cause of the error:
- A description of the error. Retrieve the
Stringobject that contains this description by calling the methodSQLException.getMessage.- A SQLState code. These codes and their respective meanings have been standardized by ISO/ANSI and Open Group (X/Open), although some codes have been reserved for database vendors to define for themselves. This
Stringobject consists of five alphanumeric characters. Retrieve this code by calling the methodSQLException.getSQLState.- An error code. This is an integer value identifying the error that caused the
SQLExceptioninstance to be thrown. Its value and meaning are implementation-specific and might be the actual error code returned by the underlying data source. Retrieve the error by calling the methodSQLException.getErrorCode.- A cause. A
SQLExceptioninstance might have a causal relationship, which consists of one or moreThrowableobjects that caused theSQLExceptioninstance to be thrown. To navigate this chain of causes, recursively call the methodSQLException.getCauseuntil anullvalue is returned.- A reference to any chained exceptions. If more than one error occurs, the exceptions are referenced through this chain. Retrieve these exceptions by calling the method
SQLException.getNextExceptionon the exception that was thrown.Retrieving Exceptions
The following method,JDBCTutorialUtilities.printSQLExceptionoutputs the SQLState, error code, error description, and cause (if there is one) contained in theSQLExceptionas well as any other exception chained to it:
public static void printSQLException(SQLException ex) { for (Throwable e : ex) { if (e instanceof SQLException) { if (ignoreSQLException(((SQLException)e).getSQLState()) == false) { e.printStackTrace(System.err); System.err.println("SQLState: " + ((SQLException)e).getSQLState()); System.err.println("Error Code: " + ((SQLException)e).getErrorCode()); System.err.println("Message: " + ((SQLException)e).getMessage()); Throwable t = ex.getCause(); while(t != null) { System.out.println("Cause: " + t); t = t.getCause(); } } } } }For example, if you call the methodCoffeesTable.dropTablewith Java DB as your DBMS, the tableCOFFEESdoes not exist, and you remove the call toJDBCTutorialUtilities.ignoreSQLException, the output will be similar to the following:
SQLState: 42Y55 Error Code: 30000 Message: 'DROP TABLE' cannot be performed on 'TESTDB.COFFEES' because it does not exist.Instead of outputtingSQLExceptioninformation, you could instead first retrieve theSQLStatethen process theSQLExceptionaccordingly. For example, the methodJDBCTutorialUtilities.ignoreSQLExceptionreturnstrueif the SQLState> is equal to code42Y55(and you are using Java DB as your DBMS), which causesJDBCTutorialUtilities.printSQLExceptionto ignore theSQLException:
public static boolean ignoreSQLException(String sqlState) { // X0Y32: Jar file already exists in schema if (sqlState.equalsIgnoreCase("X0Y32")) return true; // 42Y55: Table already exists in schema if (sqlState.equalsIgnoreCase("42Y55")) return true; return false; }Retrieving Warnings
SQLWarningobjects are a subclass ofSQLExceptionthat deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. For example, a warning might let you know that a privilege you attempted to revoke was not revoked. Or a warning might tell you that an error occurred during a requested disconnection.
A warning can be reported on aConnectionobject, aStatementobject (includingPreparedStatementandCallableStatementobjects), or aResultSetobject. Each of these classes has agetWarningsmethod, which you must invoke in order to see the first warning reported on the calling object. IfgetWarningsreturns a warning, you can call theSQLWarningmethodgetNextWarningon it to get any additional warnings. Executing a statement automatically clears the warnings from a previous statement, so they do not build up. This means, however, that if you want to retrieve warnings reported on a statement, you must do so before you execute another statement.
The following methods fromJDBCTutorialUtilitiesillustrate how to get complete information about any warnings reported onStatementorResultSetobjects:
public static void getWarningsFromResultSet(ResultSet rs) throws SQLException { JDBCTutorialUtilities.printWarnings(rs.getWarnings()); } public static void getWarningsFromStatement(Statement stmt) throws SQLException { JDBCTutorialUtilities.printWarnings(stmt.getWarnings()); } public static void printWarnings(SQLWarning warning) throws SQLException { if (warning != null) { System.out.println("\n---Warning---\n"); while (warning != null) { System.out.println("Message: " + warning.getMessage()); System.out.println("SQLState: " + warning.getSQLState()); System.out.print("Vendor error code: "); System.out.println(warning.getErrorCode()); System.out.println(""); warning = warning.getNextWarning(); } } }The most common warning is aDataTruncationwarning, a subclass ofSQLWarning. AllDataTruncationobjects have a SQLState of01004, indicating that there was a problem with reading or writing data.DataTruncationmethods let you find out in which column or parameter data was truncated, whether the truncation was on a read or write operation, how many bytes should have been transferred, and how many bytes were actually transferred.
Categorized SQLExceptions
Your JDBC driver might throw a subclass ofSQLExceptionthat corresponds to a common SQLState or a common error state that is not associated with a specific SQLState class value. This enables you to write more portable error-handling code. These exceptions are subclasses of one of the following classes:
See the latest Javadoc of the
SQLNonTransientExceptionSQLTransientExceptionSQLRecoverableExceptionjava.sqlpackage or the documentation of your JDBC driver for more information about these subclasses.
Other Subclasses of SQLException
The following subclasses ofSQLExceptioncan also be thrown:
BatchUpdateExceptionis thrown when an error occurs during a batch update operation. In addition to the information provided bySQLException,BatchUpdateExceptionprovides the update counts for all statements that were executed before the error occurred.SQLClientInfoExceptionis thrown when one or more client information properties could not be set on a Connection. In addition to the information provided bySQLException,SQLClientInfoExceptionprovides a list of client information properties that were not set.
No comments:
Post a Comment