I've read some beginner's introductions to smalltalk and there is one topic that's missing. It's error handling. How is it done? Do objects throw some kind of exceptions? Send some error messages to someone?
To raise an exception:
MyException signal.
MyException signal: 'With an error message'.
To handle an exception:
[ 1 / 0 ] on: ZeroDivide do: [ Transcript showln: 'Oops! Zero divide!'].
To handle an exception and use some of the exception's information:
[ 1 / 0 ] on: Error do:
[:e | Transcript showln: 'Oops! ' , e className , '!'].
To ensure something always happens (a la try finally
):
[ 1 / 0 ] ensure: [ Transcript showln: 'This will always run' ]
I just want to point out that beside the way @Frank Shearar mention there is an other possibility. I mean by design. Sometime is more useful to let the caller now what trouble is going throw.
The #on:do:
is perfectly acceptable but most of the time you don't know what to put as a first argument. block on: ?? do: something
.
Let take me an example. Actually there is an example from the Collection library. Especially regarding dictionary.
aDict at: 4
Here what happen if 4
isn't in the dictionary. You just get a plain Error that you need to catch in a #on:do:
.
But there is a better way to handle this situation:
aDict at: 4 ifAbsent: [^#noSuchThingAs4]
You are handle the error the same as the #on:do:
but now you know why.
So you could do that in other to handle properly your error.
aConnection connectIfFailed: [ ^#maybeRetryHere ]
Be aware that you need to put the exception code in a block so that it won't be evaluate until the error happen.
aDict at: 4 ifAbsentPut: self default
may work but it is wrong. Hope that help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With