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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With