开发者

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 o开发者_运维百科bjects 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.


Read the Pharo By Example 2 chapter: https://gforge.inria.fr/frs/download.php/26600/PBE2-Exceptions-2010-03-02.pdf

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜