loading...

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

konyu profile image @kon_yu ・1 min read

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

execution result

> method
"init,"
"FIRST RESCUE,"
"SECOND RESCUE"

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

execution result

> method2
"init,"
"FIRST RESCUE,"
"SECOND RESCUE"

Discussion

pic
Editor guide