【问题标题】:How to repeatedly handle an exception until proper result?如何重复处理异常直到正确的结果?
【发布时间】:2013-07-20 13:55:51
【问题描述】:

我有一个自定义异常,我希望在执行该方法导致错误时多次引发和救援。我知道它最终会导致无异常结果。

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

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

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

【问题讨论】:

    标签: ruby exception exception-handling rescue


    【解决方案1】:

    你可以使用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 循环中。

    【讨论】:

    • 谢谢。两者都回答了我的问题,并促使我找到了更好的实施方式。
    猜你喜欢
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    相关资源
    最近更新 更多