158 DB2 for z/OS and WebSphere: The Perfect Couple
7.3.4 SQL exceptions and SQL warnings
With the focus on DB2, we have a closer look at errors originating from the database, which
can either be an SQLException or an SQLWarning. An SQLException is generated in these
circumstances:
򐂰 When any SQL statement returns a negative SQL error code
򐂰 When a SELECT INTO SQL statement returns a SQL error code larger than 100
Any other error code on a SELECT INTO SQL statements, which corresponds to DB2
warnings, does not throw an SQLException. Instead, a SQLWarning is created, which is then
silently added to the calling object. It is therefore obvious that we must handle exceptions and
warnings in different ways.
SQLException
This is an actual exception that is thrown by the JDBC driver. This means that we must catch
the exception in our Bean. SQLException is a subclass of java.lang.Exception and is
therefore a checked exception. This means that we have to catch the exception in our Bean
code if we want to roll back the transaction. In Example 7-10 we show how to do this.
Example 7-10 Handling of a SQLException
#sql public static context MyContext with (dataSource=”jdbc/ITSO1”);
try {
MyContext context = new MyContext();
#sql [context] { INSERT INTO EMP VALUES (‘123’,,,)};
}
catch ( SQLException e ) {
throw new EJBException( e);
}
If the SQLJ statements are separated from the enterprise Beans and written in separate Java
utility classes, we just propagate any application exception, including SQLException, to the
calling client. The utility classes are often unaware of the context in which their methods are
invoked. It is therefore unlikely that the utility classes can perform any sensible error
handling—this is left to where the business logic is implemented in the session Beans.
SQLWarning
As SQLWarnings are not thrown, we are obviously not able to catch them. SQLWarnings are
added silently to the
execution context. Each SQLJ statement is associated with an execution
context. The execution context allows us to control how the statement is executed, and to
retrieve information about the statement after the execution. We can, for instance, set a query
time-out for the statement, or we can retrieve information about how many rows were affected
by a statement. We can retrieve any SQLWarnings through the execution context. For more
information about the execution context, see section 10.7 in DB2 for z/OS and 390: Ready for
Java, SG24-6435.
Important: The container does not roll back the transaction when an application exception
is thrown.
Usually we catch any application exception, checked exception, in the Bean, nest it into an
EJBException, and then throw the EJBException to tell the container to roll back the
transaction.

Get DB2 for z/OS and WebSphere: The Perfect Couple 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.