Simple exception handling is accomplished with methods that take a handler, usually a block. Some of these methods are very well-known and commonly used.
Perhaps the most frequently used of these methods is Dictionary>>at:ifAbsent:. This method takes a key and a block. The block is simply a deferred statement that takes the control when the key is not in the dictionary. In a sense, the block is an exception handler for a very special exceptional situation:
| dict | dict := Dictionary new. dict at: 'dog' put: 'Hund'. dict at: 'cat' ifAbsent: ['* unknown word *']
A similar method is Collection>>detect:ifNone:. This method takes two blocks, one that defines a search condition and one that serves as an exception handler for the special situation 'nothing found':
| collection foundItem | collection := #(#('dog' 'Hund') #('cat' 'Katze') #('snake' 'Schlange')). foundItem := collection detect: [:item | item first = 'bird'] ifNone: []. foundItem
A very special feature is available to catch a message that is not understood by its receiver. It is the method doesNotUnderstand:, which is part of the instance protocol of Object.
There are two methods that provide simple exception handling for the statements of a block. These are ifError: and ensure:.
Example for the use of ifError::
ifError: is a message that is sent to a block. The argument of ifError: is a block that is evaluated when the evaluation of the receiver signals an otherwise unhandled exception that is derived from Error. In a sense, ifError: is a 'catch-all' handler for Errors.
| dict | dict := Dictionary new. dict at: 'dog' put: 'Hund'. [dict at: 'cat'] ifError: ['* unknown word *']
Example for the use of ensure::
ensure: is a message that is sent to a block. The argument of ensure: is a block that is evaluated under all circumstances immediately after evaluation of the receiver. This method can be used to close files, to restore cursors and to restore clipping rectangles.
showWhile: aBlock " While evaluating the argument, aBlock, make the receiver be the cursor shape. " | oldCursor | oldCursor := Sensor currentCursor. self show. ^aBlock ensure: [oldCursor show]
The ensure:-block is not really an exception handler, in fact it is a finalizer that is called when a block is left. This happens
|