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

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


You can only use rescue in two cases:

  • Within a begin ... end block

    begin  raiserescue   nilend
  • 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.


As said in recent comment, response has changed since Ruby 2.5.

do ... end blocks are now implicit begin ... end blocks; like module, class and method bodies.

In-line blocks {...} still can't.