DEV Community

@kon_yu
@kon_yu

Posted on

Error handling in begin rescue verifies that errors encountered during rescue can be rescued.

Prerequisites.

Verification Version: Ruby2.6.1

Summary

We can do it.

Validation Methods
raise raises the error, rescue catches the error, in which it raises the error again, and rescue catches it

def method
  p 'init'
  begin
    raise "first error"
  rescue
    P "FIRST RESCUE"
    begin
      raise 'second error'
    rescue
      P 'SECOND RESCUE'
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

execution result

> method
"init,"
"FIRST RESCUE,"
"SECOND RESCUE"
Enter fullscreen mode Exit fullscreen mode

There's also a way to write a RESCUE one step out of the block without writing a BEGIN like this

def method2
  p 'init'
  raise "first error"
rescue
  P "FIRST RESCUE"
  begin
    raise 'second error'
  rescue
    P 'SECOND RESCUE'
  end
end
Enter fullscreen mode Exit fullscreen mode

execution result

> method2
"init,"
"FIRST RESCUE,"
"SECOND RESCUE"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)