Examples of exception handling
The follow examples show how to handle various situations:
Example: printing an object
"Assume that printString will call self error: if it encounters an error condition."
| anObject |
[ anObject printString ]
when: ExError
do: [:signal |
exitWith: [ 'Exception: ', signal argument, 'while printing a ', anObject class name ].
Example: trapping user break
"Unbreakable code"
[ 1000 timesRepeat: [ String new: 100000 ] ]
when: ExUserBreak
do: [:signal |
System confirm: 'Caught user break'.
signal resumeWith: nil ].
Example: growing a stack
"Assume that a Stack class with a push: method exists in the application."
(OverflowException := ExAll newChild)
description: 'stack overflow'.
[ aStack push: anInteger ]
when: OverflowException
do: [:signal |
aStack grow.
signal retry ].
Example: propagating a different exception
| aDifferentException |
(aDifferentException := ExAll newChild)
description: 'this is a different exception'.
[ 1 error: 'demonstration' ]
when: ExError
do: [:signal |
aDifferentException signal ]
Example: top-level loop
| loopExitException |
loopExitException := ExAll newChild.
[ [true] whileTrue: [
"Body of loop; can only be exited by sending 'loopExitException signal'."
(System confirm: 'Signal the loopExitException')
ifTrue: [ loopExitException signal ].
"Create a doesNotUnderstandException."
1 error: 'This is for demonstration purposes' ]
when: loopExitException
do: [:signal |
signal exitWith: 'bye' ]
when: ExAll
do: [:signal |
System message: 'An Exception has occurred: ', signal description.
signal retry ].
Example: close stream at end or on error
"If an error occurs, it is reported normally, but aStream is closed first."
| aStream |
aStream := ReadStream on: 'This is a test'.
[ [ aStream atEnd ]
whileFalse: [ Transcript nextPut: aStream next ]
] atEndOrWhenExceptionDo: [
Transcript show: '...Closing the stream'.
aStream close ]
Last modified date: 01/29/2015