Is nested begin/rescue/ensure valid?
Asked Answered
Q

1

15

This seems okay to me and I cannot find any documentation that says otherwise, but I'd like it verified. I have a piece of code that could fail, for whatever reason, an ensure after it to protect it if it does fail, then the need to execute some code regardless of what happens. This seems to need a nested begin/ensure block. Is that valid? (There is no actual rescue here, just that type of block.)

The code looks like:

  begin
    # save default state
    begin
      # save current state
      # set state for this snippet
      # snippet
    ensure
      # return current state or default if none
    end
  ensure
    # schedule next execution of this code, always.
  end
Quincentenary answered 6/10, 2015 at 18:3 Comment(4)
here is detailed article about it: skorks.com/2013/04/ruby-why-u-no-have-nested-exceptionsCalaverite
@asiniy Interesting article regarding the issues around it, but it states: "Ruby doesn’t allow us to nest exceptions." What? Nesting exceptions is inherent in the language, unless I totally misunderstand the statement.Quincentenary
@asiniy That article is talking about something completely different. It isn't relevant to this question at all.Untangle
Another, more recent resource: avdi.codes/exception-causes-in-ruby-2-1Masuria
Y
14

That is a perfectly valid approach. Nesting is often needed, sometimes in the same method as you've done here, and sometimes via the call stack.

Yoruba answered 6/10, 2015 at 18:12 Comment(1)
meagar, you are absolutely correct. Thank you. An error in either getting or setting the state would have tripped up my solution. Have edited my answer to reflect your astute observation.Yoruba

© 2022 - 2024 — McMap. All rights reserved.