如何重复处理异常直到正确结果?

时间:2013-07-21 21:48:56

标签: ruby exception exception-handling rescue

我有一个自定义异常,我想要提升并获救多次,因为执行该方法会导致错误。我知道它最终会导致无异常结果。

使用begin / rescue / end,似乎抛出异常并调用了rescue块,如果再次抛出异常,程序将离开begin / rescue / end块,错误将结束程序。如何在程序达到正确结果之前保持程序运行?另外,我对正在发生的事情的看法不正确吗?

这基本上就是我想要发生的事情(但显然是尽可能使用代码干......这段代码只是为了说明而不是我实现的内容。)

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

1 个答案:

答案 0 :(得分:3)

您可以使用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

无论如何,我不得不说你不应该使用异常作为控制流。我建议您,如果预计place_ship失败,则应返回true / false结果,并且您应该将代码包含在标准do while循环中。