本文介绍了在Ruby中,可以嵌套`rescue`语句的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ruby中,为了捕获错误,使用 rescue 语句。一般来说,这个陈述发生在 begin end 之间。还可以使用 rescue 语句作为块的一部分( do ... end )或方法( def ... end )。我的问题是什么其他的结构(循环,while,if,...)如果有什么会救援巢?

In ruby to catch an error one uses the rescue statement. generally this statement occurs between begin and end. One can also use a rescue statement as part of a block (do ... end) or a method (def ... end). My question is what other structures (loop, while, if, ...) if any will rescue nest within?

推荐答案

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

You can only use rescue in two cases:


  • 开始...结束

begin
  raise
rescue
  nil
end


  • 作为语句修饰符

  • As a statement modifier

    i = raise rescue nil
    


  • 函数,模块和类体(感谢Jörg)是隐式的开始...结束阻止,所以你可以在任何功能中拯救,而没有明确的开始 / end

    Function, module, and class bodies (thanks Jörg) are implicit begin...end blocks, so you can rescue within any function without an explicit begin/end.

        def foo
          raise
        rescue
          nil
        end
    

    块表单接受可选的参数列表,指定哪些异常(和后代)为 rescue

    The block form takes an optional list of parameters, specifying which exceptions (and descendants) to 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 块中没有参数,抢救将捕获。

    这篇关于在Ruby中,可以嵌套`rescue`语句的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    09-14 09:05