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
Richard_G
  • 4,700
  • 3
  • 42
  • 78
  • 1
    here is detailed article about it: http://www.skorks.com/2013/04/ruby-why-u-no-have-nested-exceptions/ – Alex Antonov Oct 06 '15 at 18:05
  • @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. – Richard_G Oct 06 '15 at 18:21
  • @asiniy That article is talking about something completely different. It isn't relevant to this question at all. – user229044 Oct 06 '15 at 18:32
  • Another, more recent resource: https://avdi.codes/exception-causes-in-ruby-2-1/ – Rimian Jun 06 '21 at 23:36

1 Answers1

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.

Brian
  • 967
  • 7
  • 12
  • 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. – Brian Oct 06 '15 at 18:20