From: "jeremyevans0 (Jeremy Evans)" Date: 2022-10-14T14:53:47+00:00 Subject: [ruby-core:110285] [Ruby master Misc#19054] `else` in exception-handling context vs early return Issue #19054 has been updated by jeremyevans0 (Jeremy Evans). I think the existing behavior is expected. `else` with `rescue` operates similar to `else` with `if`. In pseudocode: ```ruby begin if e = exception_raised_by{puts "body"; return} p e else puts "else" end ensure puts "ensure" end ``` I agree with you that the documentation could be improved, though it kind of hints at the current behavior: * (Regarding `else`): "You may also run some code when an exception is not raised" * "To always run some code whether an exception was raised or not, use ensure:" It would be useful to document that else is not called on early exits or exceptions, and how to use `ensure` to run code on all non-exception scenarios (by using `rescue => local_var` and `if local_var`). ---------------------------------------- Misc #19054: `else` in exception-handling context vs early return https://bugs.ruby-lang.org/issues/19054#change-99571 * Author: zverok (Victor Shepelev) * Status: Open * Priority: Normal ---------------------------------------- `else` in exception-handling context is rarely used (at least in codebase I saw), so we encountered it just recently: ```ruby def foo puts "body" return rescue => e p e else puts "else" ensure puts "ensure" end foo # prints "body", then "ensure" [1].each do puts "body" next rescue => e p e else puts "else" ensure puts "ensure" end # also prints "body" then "ensure" ``` E.g. `else` is ignored in both cases. Intuitively, I would expect that if no exception is raised in block, `else` is performed always���like `ensure` is performed always, exception or not, early return or not. I found only a very old discussion of this behavior in #4473 (it was broken accidentally on the road to 1.9.2, but then fixed back), but it doesn't explain the reason for it. Can somebody provide an insight on this decision, and whether it is justified at all?.. At least, it should be documented somewhere, [exception handling docs](https://docs.ruby-lang.org/en/master/syntax/exceptions_rdoc.html) doesn't mention this quirk. -- https://bugs.ruby-lang.org/ Unsubscribe: