简体   繁体   中英

How to repeatedly handle an exception until proper result?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM