Kyle Chickering Kyle Chickering - 5 months ago 9
Ruby Question

Accessing Error Messages within a Rescue Block

Is there any way to get access to an error message in a rescue block as a string? For example:

def foo
raise RuntimeError, "This is an error"
end

def bar
begin
foo
rescue RuntimeError
puts "Rescued"
end
end

bar


Is there any way to gain access to
"This is an error"
from with-in the rescue block? Something like this:

...
rescue RuntimeError
puts <error-message>
end
...

Answer

You need to specify a variable to store the error in

def foo
  raise RuntimeError, "This is an error"
end

def bar
  begin
    foo
  rescue RuntimeError => ex
    puts "Rescued #{ex.message}"
  end
end