代码之家  ›  专栏  ›  技术社区  ›  John F. Miller

在Ruby中,“rescue”语句可以嵌套在什么结构中

  •  31
  • John F. Miller  · 技术社区  · 16 年前

    rescue 声明。通常这种说法发生在 begin end . 也可以使用 语句作为块的一部分( do ... end )或者一种方法( def ... end

    1 回复  |  直到 16 年前
        1
  •  45
  •   klochner    14 年前

    • 在一个 begin ... end

      begin
        raise
      rescue 
        nil
      end
      
    • i = raise rescue nil
      

    函数、模块和类主体(感谢Jrg)是隐式的 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
    

    如果作为语句修饰符内联调用,或在 开始 / 结束 StandardError and its descendants .

    这是你的答案 1.9 documentation on rescue .

        2
  •  3
  •   pimpin    5 年前

    recent comment ,响应已更改 since Ruby 2.5

    do ... end 块现在是隐式的 begin ... end

    直列块 {...}

    推荐文章