RocketGuy3
RocketGuy3

Reputation: 625

How can I raise an exception down the stack in Ruby?

If I have a function foo_1 that calls foo_2, and foo_2 can raise an exception that I want to handle in foo_1. How can I do that?

I want to write something like this, so that I only have to deal with one begin/rescue block:

def foo_1
  begin
    foo_2
  rescue SomeException
    # Do stuff
  end
end

def foo_2
  # Do stuff that can throw SomeException
end

How can I pass the exception from foo_2?

Upvotes: 0

Views: 59

Answers (1)

Chris Heald
Chris Heald

Reputation: 62638

If a stack frame doesn't a thrown exception, then it will automatically propagate down to the next stack frame, until it's either handled or it reaches the bottom of the stack (at which point the Ruby interpreter handles it by printing it out and your program terminating). You don't have to do anything to enable this behavior.

class SomeException < StandardError; end

def foo_1
  begin
    foo_2
  rescue SomeException => e
    "Rescued #{e.message} in foo_1"
  end
end

def foo_2
  foo_3
end

def foo_3
  raise SomeException.new("kaboom!")
end

# > foo_1
# => "Rescued kaboom! in foo_1"

Upvotes: 1

Related Questions