The follow examples show how to handle various situations:
"Assume that printString will call self error: if it encounters an error condition."
| anObject |
[ anObject printString ]
when: ExError
do: [:signal |
signal
exitWith: 'Exception: ', signal argument, 'while printing
a ', anObject class name ].
[ "Unbreakable code"
1000 timesRepeat: [String new: 100000]]
when: ExUserBreak
do: [:signal |
System confirm: 'Caught user break'.
signal resumeWith: nil ].
"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 ].
| aDifferentException |
(aDifferentException := ExAll newChild)
description: 'this is a different exception'.
[1 error: 'demonstration' ]
when: ExError
do: [:signal |
aDifferentException signal].
| loopExitException |
loopExitException := ExAll newChild.
[ [ true ] whileTrue: [
"Body of loop. Can only be exited by saying
'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 ].
"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 ].