Exception Handling

Ron Teitelbaum Ron at USMedRec.com
Mon Mar 20 20:52:41 UTC 2006


> From: nicolas cellier
> Sent: Monday, March 20, 2006 3:42 PM
>
> Le Lundi 20 Mars 2006 21:12, Zulq Alam a écrit :
> > Hello,
> >
> > I'm a bit confused about exception handling, perhaps you can help
> please?
> >
> > If I have a method #foo and #foo can signal two errors FooError and
> > UnrelatedToFooError how do I handle both errors using #on:do: without
> > having something like...
> >
> > [someObject foo]
> >     on: Error
> >     do: [:error | (error class = FooError) ifTrue: ["do something
> > specific to FooError"].
> >           (error class = UnrelatedToFooError) ifTrue: ["do something
> > specific to UnrelatedToFooError"]].
> >
> 
> If handler blocks are different, you might nest the two
> 
> [[someObject foo]
>         on: FooError
>         do: [:error | "do something specific to FooError"]]
>     on: UnrelatedToFooError
>     do: [:error | "do something specific to UnrelatedToFooError"].
> 
> It's a little like the if/elseif chain, you have to nest them in
> Smalltalk.
> Otherwise, you could try and implement your own multiple error messages
>  on:do:on:do:
>  on:do:on:do:on:do:
> 
> If handler blocks are the same, there is the possibility to handle a
> collection of errors in Visualworks,
>   [someObject foo]
>         on: FooError , UnrelatedToFooError
>         do: [:error | "do something common to FooError and
> UnrelatedToFooError"].
> 
> but i did not see anything like this in Squeak... unless i missed
> something.
> Has anyone got elegant a solution for the second case ?
> 
> Nicolas
> 
> 

Also you might keep in mind that subclasses of errors are handled also.

If FooError were a subclass of UnrelatedToFooError, then the handler for
UnrelatedToFooError would catch both.  

It's also a nice trick to put the handler on the error.  
In that case you get the following

[someObject foo]
        on: UnrelatedToFooError   "handles subclasses"
        do: [:error | error handleError].

Then 

UnrelatedToFooError >> handleError
	"Do something unrelated to Foo"

FooError >> handleError
	"Do something related to Foo"

You could also use a error handleErrorWith: aSomethingOrOther

And then you could send it some context for handling your error.  Say if the
Error wrapper is on an application then handleErrorWith: anApplication would
give your errorHandler the application that it could use for handling the
error.

Happy coding!

Ron Teitelbaum





More information about the Squeak-dev mailing list