簡體   English   中英

如何反復處理異常,直到獲得適當結果?

[英]How to repeatedly handle an exception until proper result?

我有一個自定義異常,我想引發該事件並對其進行多次挽救,因為執行該方法會導致錯誤。 我知道它將最終導致無異常結果。

使用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

您可以使用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循環中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM