Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

smalltalk error handling

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?

like image 721
milan Avatar asked Jan 29 '11 08:01

milan


2 Answers

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' ]
like image 129
Frank Shearar Avatar answered Oct 18 '22 20:10

Frank Shearar


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.

like image 40
mathk Avatar answered Oct 18 '22 20:10

mathk