Search code examples
exceptionpharo

Catch and handle (differently) different exceptions for the same block, with an ensure


I know from the MOOC documentation that it's possible to have the same handler for multiple exceptions that can occur during some block, e.g.:

[ do some work ]
on: ZeroDivide, Warning
do: [ :ex | what you want ]

In the same document, there's an example with ensure to make sure code is always executed (despite any exceptions):

[ doSomething ] ensure: [ alwaysExecuteThis ]

However, I would like something like:

[ do some work ]
on: ZeroDivide
do: [ :zeroDivide | handle it ]
on: Warning
do: [ :warning | handle it ]
ensure: [ alwaysExecuteThis ]

Admittedly, this is my Java experience influencing how I want to use Pharo.


Solution

  • It seems it's possible using nested blocks:

    [ [ [ [ doSomething here ]
        on: ZeroDivide
        do: [ :zeroEx | 'zeroExc' crLog ] ]
        on: Warning
        do: [ :warning | 'warning' crLog ] ]
        ensure: [ 'ensure' crLog ] ]