From: "Eregon (Benoit Daloze)" Date: 2021-10-19T17:51:58+00:00 Subject: [ruby-core:105682] [Ruby master Feature#18083] Capture error in ensure block. Issue #18083 has been updated by Eregon (Benoit Daloze). ko1 (Koichi Sasada) wrote in #note-18: > Another proposal is change `$!` semantics to `begin/rescue/ensure' clause local. > Does it solve the issues? That seems elegant actually, because ```ruby begin ... rescue foo($!) end ``` would behave like: ```ruby begin ... rescue => exc foo(exc) end ``` And it would avoid escaping the Exception instance to the thread, which mean it can be escaped analyzed. Also, if the `rescue` doesn't use `=>` or `$!`, there is no need to generate a backtrace which is a huge performance gain! With current semantics that's difficult to know as any call inside the rescue clause might use `$!`. I"m not sure regarding compatibility if e.g. `$!` is accessed inside a method called from the rescue clause. But that's probably rare and seems bad code, so I think fine to try/experiment. ---------------------------------------- Feature #18083: Capture error in ensure block. https://bugs.ruby-lang.org/issues/18083#change-94182 * Author: ioquatix (Samuel Williams) * Status: Open * Priority: Normal ---------------------------------------- As discussed in https://bugs.ruby-lang.org/issues/15567 there are some tricky edge cases. As a general model, something like the following would be incredibly useful: ``` ruby begin ... ensure => error pp "error occurred" if error end ``` Currently you can get similar behaviour like this: ``` ruby begin ... rescue Exception => error raise ensure pp "error occurred" if error end ``` The limitation of this approach is it only works if you don't need any other `rescue` clause. Otherwise, it may not work as expected or require extra care. Also, Rubocop will complain about it. Using `$!` can be buggy if you call some method from `rescue` or `ensure` clause, since it would be set already. It was discussed extensively in https://bugs.ruby-lang.org/issues/15567 if you want more details. -- https://bugs.ruby-lang.org/ Unsubscribe: