[ruby-core:105002] [Ruby master Feature#18083] Capture error in ensure block.
From:
"matz (Yukihiro Matsumoto)" <noreply@...>
Date:
2021-08-19 08:19:30 UTC
List:
ruby-core #105002
Issue #18083 has been updated by matz (Yukihiro Matsumoto). I hesitate to enhance `ensure`. It's ugly and against the basic concept of `ensure`. The `ensure` behavior was taken from `unwind-protect` macro of Lisp, and it does not distinguish between error execution and normal execution. If you check the error condition in the `ensure` clause, especially using `$!`, I doubt you misuse the `ensure` concept. If you really wanted to check the error condition, you may want to use local variables. ```ruby begin .... no_error = true ensure error_handling unless no_error end ``` At the same time, I may underestimate the pain of OP. Let me think about it for a while. Matz. ---------------------------------------- Feature #18083: Capture error in ensure block. https://bugs.ruby-lang.org/issues/18083#change-93402 * 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: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe> <http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>