
Issue #18083 has been updated by Dan0042 (Daniel DeLorme). ko1 (Koichi Sasada) wrote in #note-20:
my proposal is introducing dynamic scope, not syntactical scope like:
I think this is a good idea, definitely an improvement over the current situation. `$!` is already always correct inside a `rescue` clause, and that would make it always correct inside the `ensure` clause. But I want to confirm if this would be the expected behavior: ```ruby #1 p $! #=> A begin # no raise ensure p $! #=> nil (unlike A currently) end p $! #=> A (restored after previous begin-ensure block?) #2 p $! #=> A begin raise "B" rescue p $! #=> B #not re-raised ensure p $! #=> B (unlike A currently) end p $! #=> A (restored after previous begin-ensure block?) ``` ---------------------------------------- Feature #18083: Capture error in ensure block. https://bugs.ruby-lang.org/issues/18083#change-105683 * 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/