0

Is there any way to regain control to begin block after performing rescue block like

begin
 .....
 error(not intended but happening intermittently)
 things to execute
rescue
 describe error
end

Is there any way that my code will go to things to execute after describe error

Thanks in advance

Ram Kumar
  • 45
  • 6

1 Answers1

0

There's no goto-like construction in Ruby (fortunately). And it's not possible to use catch-throw because of begin-rescue-end block. So you can try something like this:

def error_handler
  # if this method will raise an error it's possible to catch it here
  # with `rescue` or (and) `ensure`
  p :finalize
end

def one
  1 / rand(0..3)
rescue
  error_handler
end

def two
  1 / rand(0..3)
rescue
  error_handler
end

def three
  1 / rand(0..3)
rescue
  error_handler
end

begin
  one
  two
  three
  1 / rand(0..3)
rescue => error
  error_handler
end
Psylone
  • 2,788
  • 1
  • 18
  • 15
  • Actually my `begin` will contain 20+ lines. If there is an error comes out from 5th line, it will go to `rescue` and `ensure`. But 5th line may not produce error..8 th line may produce or 10th ... even 19th line or no error..You cannot decide when the error occurs and from which line(intermittent error which may be thrown from any of the 20 lines or not).If I write only one rescue/ensure my code after the error won't execute.. Thats the problem here and I want to run whole starting from begin as whole as the lines before error already get executed before error happens – Ram Kumar Feb 15 '17 at 15:47
  • Got it. I think it's a more architectural than control flow kind of issue. You can try to encapsulate every piece of logic from the `begin` section and also hold your `some_final_operations` inside the method. – Psylone Feb 15 '17 at 15:53
  • So is there any possible way of solution to return to the begin block ?? – Ram Kumar Feb 15 '17 at 15:55
  • Can you explain some more detailed how to encapsulating those stuffs as the flow is not gonna be disturbed and let it have to flow like stream..Thanks in advance – Ram Kumar Feb 15 '17 at 16:02
  • There's no `goto`-like in Ruby. And you can't also use `catch-throw` construction because of `begin-rescue-end` block. Please see modified answer above with the possible solution. – Psylone Feb 15 '17 at 16:02
  • Thanks Psylone for your interest and my `perform_finalization` may throw errors...I too can't find any solution for my problem as of now. Will try to remodel the structure if supports. – Ram Kumar Feb 15 '17 at 16:07
  • You can add `rescue` inside the `perform_finalization` method. If you'll get an error say in `one` method, it will raise an error and call `perform_finalization`. If it also will raise an error, you can catch it and after that, your flow will return to the point of calling `one` method, so your execution flow will be continued. Anyway, to remodel this flow looks like a good idea ) – Psylone Feb 15 '17 at 16:17