Richard_G
Richard_G

Reputation: 4820

Is nested begin/rescue/ensure valid?

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

Upvotes: 15

Views: 8466

Answers (1)

Brian
Brian

Reputation: 967

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.

Upvotes: 14

Related Questions