Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 832
Richard_G Avatar asked Oct 06 '15 18:10

Richard_G


People also ask

What is ensure Ruby?

Sometimes, all you want to do is make sure that a specific piece of code will always run! Luckily, that's what the ensure keyword is for. This keyword starts a section of code that is always run when an exception is raised. And just like rescue , it's written at the same level as our method's signature.

What does Ruby Rescue do?

A raised exception can be rescued to prevent it from crashing your application once it reaches the top of the call stack. In Ruby, we use the rescue keyword for that. When rescuing an exception in Ruby, you can specify a specific error class that should be rescued from.

What is begin and rescue in rails?

The code between “begin” and “rescue” is where a probable exception might occur. If an exception occurs, the rescue block will execute. You should try to be specific about what exception you're rescuing because it's considered a bad practice to capture all exceptions.


1 Answers

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.

like image 153
Brian Avatar answered Sep 25 '22 02:09

Brian