【问题标题】:How to resume from rescue clause in Ruby?如何从 Ruby 中的救援子句恢复?
【发布时间】:2014-02-27 19:01:09
【问题描述】:

如何在 Ruby 中将恢复写入循环?这是一个示例代码。

#!/usr/bin/ruby
#

a = [1,2,3,4,5]

begin
    a.each{|i|
        puts i
    if( i==4 ) then raise StandardError end # Dummy exception case
    }
rescue =>e
  # Do error handling here
  next # Resume into the next item in 'begin' clause
end

但是,当运行时,Ruby 返回错误信息

test1.rb:13: Invalid next
test1.rb: compile error (SyntaxError)

我使用的是 Ruby 1.9.3。

【问题讨论】:

    标签: ruby exception rescue


    【解决方案1】:

    您应该使用retry 而不是next;但是这样会导致死循环(retrybegin的开头重启)

    a = [1,2,3,4,5]
    begin
        a.each{|i|
            puts i
            if  i == 4 then raise StandardError end
        }
    rescue =>e
        retry # <----
    end
    

    如果您想跳过一个项目并继续下一个项目,请在循环内捕获异常。

    a = [1,2,3,4,5]
    a.each{|i|
        begin
            puts i
            if  i == 4 then raise StandardError end
        rescue => e
        end
    }
    

    【讨论】:

      【解决方案2】:

      将您的异常捕获移动到 each 块中,例如:

      a = [1,2,3,4,5]
      a.each do |i|
        puts i
        begin
        # Dummy exception case
        if( i==4 ) then raise StandardError end
      
        rescue =>e
          # Do error handling here
        end
      end
      

      【讨论】:

      • 我认为你不需要next,bihaid。
      • @CarySwoveland 是的,我没有仔细考虑代码,我只是修改了 OP 的代码以反映他需要做的事情,next 正如你所观察到的那样,这里真的不会有什么不同,谢谢,对我的手柄很好:)
      • 啊,是的,把它变成一个j。
      • begin .. rescue 不包含任何声明。
      猜你喜欢
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 2014-12-31
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      相关资源
      最近更新 更多