2013-07-21 8 views
0

메서드를 수행 할 때 오류가 발생하는 것처럼 사용자 지정 예외를 제기하고 여러 번 구조해야합니다. 나는 그것이 결과적으로 예외적 인 결과를 가져올 것이라는 것을 알고있다.올바른 결과가 나올 때까지 반복적으로 예외를 처리하는 방법은 무엇입니까?

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 

답변

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

감사합니다. 둘 다 내 질문에 대답하고 구현할 수있는 더 좋은 방법을 찾게했습니다. –