IT TIP

Ruby : 예외 포착 후 루프 계속

itqueen 2020. 12. 2. 22:20
반응형

Ruby : 예외 포착 후 루프 계속


기본적으로 다음과 같은 작업을하고 싶습니다 (Python 또는 유사한 명령형 언어).

for i in xrange(1, 5):
    try:
        do_something_that_might_raise_exceptions(i)
    except:
        continue    # continue the loop at i = i + 1

Ruby에서 어떻게해야합니까? redoretry키워드 가 있다는 것을 알고 있지만 루프를 계속하는 대신 "try"블록을 다시 실행하는 것 같습니다.

for i in 1..5
    begin
        do_something_that_might_raise_exceptions(i)
    rescue
        retry    # do_something_* again, with same i
    end
end

Ruby에서는 continue철자가 next.


for i in 1..5
    begin
        do_something_that_might_raise_exceptions(i)
    rescue
        next    # do_something_* again, with the next i
    end
end

예외를 인쇄하려면 :

rescue
        puts $!, $@
        next    # do_something_* again, with the next i
end

참고 URL : https://stackoverflow.com/questions/2624835/ruby-continue-a-loop-after-catching-an-exception

반응형