Advanced Database Feature Guide


Exception Handling

Whenever an SQL error occurs and a CLI function returns a negative number, a UtyDB2Error exception will be raised. If left unhandled, this exception will cause a walkback to occur. However, these exceptions can be handled in a number of ways. The first way involves standard Smalltalk exception handling as illustrated in the following example:

[ connection executeSql: 'DROP TABLE NOTABLE' ] 
when: UtyDB2Exceptions::UtyDB2Error 
do: [ :sig | sig exitWith: sig callStatus sqlstate ]. 
 

Another way involves using the xxxIfError: methods implemented by various classes throughout the Advanced Database feature. The last parameter for any of these methods is an error block with zero or one parameter. If a one-parameter block is used, the call status describing the error is passed to the block when it is evaluated. The following example shows how to use both types of parameter blocks.

"Example of how to use a zero parameter error block." 
result := 
connection 
executeSql: 'DROP TABLE NOTABLE' 
ifError: [ nil ]. 
Result isNil ifTrue: [ self error: 'Couldn't drop table' ]. 
"Example of how to use a one parameter error block." 
connection 
executeSql: 'DROP TABLE NOTABLE' 
ifError: [ :cs | cs sqlcode ~= -204 ifTrue: [ cs signal ] ]. 
 

The last and perhaps least desirable mechanism for handling exceptions involves the use of default error blocks. The UtyDB2DatabaseManager, UtyDB2Connection and UtyDB2Statement objects can all be configured to have default error blocks. However, these error blocks work in a more passive manner than those above. The when:do: and ifError: mechanism for handling error are much more aggressive at capturing the error than default error blocks. In other words, default error blocks are only invoked if there is no one else who will capture an error. For example, if an application has defined a default error block on a database manager class then that error block is only invoked if there are no default error blocks supplied at either the connection or statement level. In addition, the code that caused the exception must not be inside of a when:do: block and the code must not use an xxxIfError: method.

UtyDB2DatabaseManager errorBlock: [ #manager ]. 
"This code will return #ifError." 
connection 
executeSql: 'DROP TABLE NOTABLE' 
ifError: [ #ifError ]. 
"This code will return #when:do:" 
[ connection executeSql: 'DROP TABLE NOTABLE' ] 
when: UtyDB2Exceptions::UtyDB2Error 
do: [ :sig | sig exitWith: #when:do: ]. 
"This code will return #manager" 
connection executeSql: 'DROP TABLE NOTABLE' 
"This code will return #connection" 
connection errorBlock: [ #connection ]. 
connection executeSql: 'DROP TABLE NOTABLE' 
 


[ Top of Page | Previous Page | Next Page | Table of Contents | Index ]