Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-catch-finally idiom in smalltalk

How do you realize a try-catch-finally idiom in smalltalk? I see there is on:do: and ensure:, but there isn't on:do:ensure:. I must be missing something.

like image 778
milan Avatar asked Oct 20 '11 18:10

milan


4 Answers

You could wrap the #on:do block in another block that has the #ensure: attached to it.

like image 178
mamboking Avatar answered Nov 01 '22 11:11

mamboking


If you really need it, you can add a protocol to BlockClosure:

#on: anErrorOrSet do: errorBlock ensure: finallyBlock
    [ self on: anErrorOrSet do: errorBlock ]
    ensure: finallyBlock

that will behaves just like try:catch:finally: on java.

That's the magic of smalltalk (well, a small part of it), if there is no match for your needs, you can always extend it :)

like image 33
EstebanLM Avatar answered Nov 01 '22 12:11

EstebanLM


I'm not sure I understood your question, but if I did and you meant "how does one handle an exception if it is triggered and continue the normal execution otherwise", this is what you can do:

[self doWhatever] on: SomeException do: [self handleSomeException].
self continueNormally.

Check out all subclasses of Exception to see what kind of exceptions you can capture.

Hope it helped!

like image 1
Bernat Romagosa Avatar answered Nov 01 '22 11:11

Bernat Romagosa


This is how you can write it out of the box in almost all Smalltalk dialects.

[[ "try{}" ] 
    on: Error 
    do: [:ex | "catch{}"]]
        ensure: ["finally{}"]

Or you can extend BlockClosure as @EstebanLM recommended.

like image 1
Esteban A. Maringolo Avatar answered Nov 01 '22 11:11

Esteban A. Maringolo