In Ruby, What structures can a `rescue` statement be nested in

前端 未结 1 785
甜味超标
甜味超标 2020-12-24 11:45

In ruby to catch an error one uses the rescue statement. generally this statement occurs between begin and end. One can also use a

1条回答
  •  無奈伤痛
    2020-12-24 12:30

    You can only use rescue in two cases:

    • Within a begin ... end block

      begin
        raise
      rescue 
        nil
      end
      
    • As a statement modifier

      i = raise rescue nil
      

    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
    

    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
    

    If called inline as a statement modifier, or without argument within a begin/end block, rescue will catch StandardError and its descendants.

    Here's the 1.9 documentation on rescue.

    0 讨论(0)
提交回复
热议问题