【问题标题】:In Ruby, What structures can a `rescue` statement be nested in在 Ruby 中,“rescue”语句可以嵌套在哪些结构中
【发布时间】:2011-02-01 06:09:42
【问题描述】:

在 ruby​​ 中使用rescue 语句来捕获错误。通常此语句出现在beginend 之间。也可以将rescue 语句用作块(do ... end)或方法(def ... end)的一部分。我的问题是如果有其他结构(循环、while、if、...)可以在其中拯救巢穴?

【问题讨论】:

  • do ... end 没有明确的begin ... end 就无法拯救块。
  • 因为ruby 2.5 do ... end 块可以在没有明确的begin ... end 的情况下被拯救。

标签: ruby syntax error-handling


【解决方案1】:

只能在两种情况下使用救援:

  • begin ... end 块内

    begin
      raise
    rescue 
      nil
    end
    
  • 作为语句修饰符

    i = raise rescue nil
    

函数、模块和类主体(感谢 Jörg)是隐式的 begin...end 块,因此您可以在没有显式 begin/end 的任何函数中进行救援。

    def foo
      raise
    rescue
      nil
    end

块形式采用可选参数列表,指定rescue 的哪些异常(和后代):

    begin
      eval string
    rescue SyntaxError, NameError => boom
      print "String doesn't compile: " + boom
    rescue StandardError => bang
      print "Error running script: " + bang
    end

如果调用 inline 作为语句修饰符,或者在 begin/end 块中没有参数,rescue 将捕获 StandardError and its descendants

这是1.9 documentation on rescue

【讨论】:

  • moduleclass 正文也是隐含的 begin 块。
  • @Jörg W Mittag:do ... end 块和 def ... end 方法定义也是如此。还有其他隐含的begin 吗?例如whilecaseif
  • @john - do...end 不是隐含的 begin...end。
  • 我建议将上面关于 do...end 的评论添加到答案中...这确实是我想要的。
  • 虽然没有很好的文档记录,但从 ruby​​ 2.5 开始,rescue 可以在常规的 do/end 块中工作(虽然不是内联块 {...})。 commit
【解决方案2】:

正如recent comment 中所说,回复已更改since Ruby 2.5

do ... end 块现在是隐含的 begin ... end 块;比如模块、类和方法体。

内嵌块{...} 仍然不能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    相关资源
    最近更新 更多