18
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rescue 節で一定回数 retry したあとは次に移るループ

Posted at

begin ~ rescue ~ end内でのnextは、rescueには関係せずに外側のループに作用するんだよな、と確認したかったのでやってみた。
(Ruby 1.9.3)

10.times do |i|
  retry_counter = 0
  begin
    raise
  rescue
    retry_counter += 1
    if retry_counter <= 5
      puts i.to_s + ": retry"
      retry
    else
      puts "retried 5 times so go to next loop"
      next
    end
  end
end

結果

0: retry
0: retry
0: retry
0: retry
0: retry
retry 5 times so go to next loop
1: retry
1: retry
1: retry
1: retry
1: retry
retry 5 times so go to next loop

(中略)

9: retry
9: retry
9: retry
9: retry
9: retry
retry 5 times so go to next loop

そういえば、(1.9以降だと)retryは繰り返し構造に作用しないし、繰り返し構造でのやり直しはredoだと思い出したのは、コレを書き終えたあとでしたw

###redo
ループ条件のチェックを行なわず、現在の繰り返しをやり直します。

###retry
retry は、rescue 節で begin 式をはじめからもう一度実行するのに使用します。
制御構造(るりま 1.9.3)

18
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?