捕获并处理(不同地)同一块的不同异常,并确保

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

我从 the MOOC documentation 了解到,对于某些块中可能发生的多个异常,可以使用相同的处理程序,例如:

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

在同一文档中,有一个示例 ensure 以确保始终执行代码(尽管有任何例外):

[ doSomething ] ensure: [ alwaysExecuteThis ]

但是,我想要这样的东西:

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

诚然,这是我的 Java 经验,影响了我使用 Pharo 的方式。

It seems it's possible 使用嵌套块:

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

尝试将此方法添加到 BlockClosure:

on: exception1
do: block1
on: exception2
do: block2
  ^self on: exception1 , exception2 do: [:ex |
    (exception1 handles: ex)
      ifTrue: [block1 value: ex]
      ifFalse: [block2 value: ex]]

请注意,exception1exception2 可以是 Exception 的子类或 ExceptionSet 的实例(使用 #, 创建)。