[comp.lang.smalltalk] Catch & throw for Smalltalks

gza@mentor.cc.purdue.edu (William R Burdick) (03/29/90)

Sometimes, I've wanted catch & throw or even just the ability to break
out of whiles without having to define a separate method to hold the
while loop, so I wrote a simple catch & throw last night.

Here's an example of its use:

	Catcher catch:[:tag |
		true ifTrue: [tag throw: #thrown].
		#notThrown]

This class will work in any Smalltalk that I know of, because it
doesn't rely on any fancy stuff, like exception handling.  It just
relys on the ability to return from the method enclosing a block.

(':=' is a synonym for the assignment operator in Smalltalk 2.5, so
you may have to use a global replace of ':=' for '_' or '<-,'
depending on your version of Smalltalk.  Also, you may or may not have
to take out all the '!'s and *** methodsFor: *** expressions.)

----- cut here -----

Object subclass: #Catcher
        instanceVariableNames: 'context '
        classVariableNames: ''
        poolDictionaries: ''
        category: 'Goodies'!

!Catcher methodsFor: 'accessing'!

context
        ^context!

context: aValue
        context := aValue! !

!Catcher methodsFor: 'controlling'!

catch: aBlock
        self context: [:returnValue | ^returnValue].
        ^aBlock value: self!

throw
        self throw: nil!

throw: value
        self context value: value! !
"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!

Catcher class
        instanceVariableNames: ''!

!Catcher class methodsFor: 'instance creation'!

catch: aBlock
        ^self new catch: aBlock! !
--
	-- Bill Burdick
	burdick@cello.ecn.purdue.edu