2013-07-21 33 views
0

我有一個自定義的異常,我想提出和拯救多少次執行該方法會導致錯誤。我知道它最終會導致異常的免費結果。如何重複處理異常,直到正確的結果?

使用開始/救援/結束它似乎是當引發異常和救援塊調用,如果再次拋出異常程序離開開始/救援/結束塊和錯誤結束程序。我如何讓程序繼續運行直到達到正確的結果?另外,我對於發生什麼事情的想法不正確?

這裏基本上是我想要發生的事情(但顯然儘可能使用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 

回答

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循環中。

+0

謝謝。兩人都回答了我的問題,並引發我採取更好的實施方式。 –