ruby - How to repeatedly handle an exception until proper result? -


i have custom exception want raised , rescued many times performing method causes error. know result in exception free result.

using begin/rescue/end seems when exception thrown , rescue block invoked, if exception thrown again program leaves begin/rescue/end block , error ends program. how can keep program running until proper result reached? also, incorrect on thinking of what's happening?

here's want happen (but dry of code possible...this code illustrate , not i'd implement).

ships.each |ship|   begin     orientation = rand(2) == 1 ? :vertical : :horizontal     cell_coords = [rand(10), rand(10)]      place_ship(ship, orientation, cell_coords)   rescue overlaperror  #if overlap error happens twice in row, leaves?     orientation = rand(2) == 1 ? :vertical : :horizontal     cell_coords = [rand(10), rand(10)]      place_ship(ship, orientation, cell_coords)   rescue overlaperror     orientation = rand(2) == 1 ? :vertical : :horizontal     cell_coords = [rand(10), rand(10)]      place_ship(ship, orientation, cell_coords)   rescue overlaperror     orientation = rand(2) == 1 ? :vertical : :horizontal     cell_coords = [rand(10), rand(10)]      place_ship(ship, orientation, cell_coords)   #keep rescuing until result exception free   end end 

you can use retry:

ships.each |ship|   begin     orientation = rand(2) == 1 ? :vertical : :horizontal     cell_coords = [rand(10), rand(10)]      place_ship(ship, orientation, cell_coords)   rescue overlaperror  #if overlap error happens twice in row, leaves?     retry   end end 

anyway, have should not use exceptions control flow. recommend , if place_ship expected fail, should return true/false result, , should include code in standard do while loop.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -