Question

I have a custom exception that I want raised and rescued for as many times as performing the method causes the error. I know that it will eventually result in a exception free result.

Using begin/rescue/end it seems like when the exception is thrown and the rescue block invoked, if the exception is thrown again the program leaves the begin/rescue/end block and the error ends the program. How can I keep the program running until the proper result is reached? Also, am I incorrect on my thinking of what's happening?

Here's basically what I want to happen (but obviously with as DRY of code as possible...this code is just to illustrate and not what I'd implement).

ships.each do |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 a row, it 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 the result is exception free
  end
end
Was it helpful?

Solution

You can use retry:

ships.each do |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 a row, it leaves?
    retry
  end
end

Anyway, I have to say that you should not use exceptions as control flow. I will recommend you , if place_ship is expected to fail, it should return true/false result, and you should include the code in a standard do while loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top