Reputation: 1636
Suppose I have the following:
begin
raise 'Exception!'
rescue => e
puts "Rescued exception: #{e.message}"
raise 'Something I did in this block raised an exception!'
end
What's the Rubyist way to catch the second exception? Is it best to wrap the entire thing in another begin-rescue block, or is there a more elegant solution?
Upvotes: 2
Views: 760
Reputation: 27799
I can't speak to the Rubyist way, but here's a Rubyist's way:
Make the rescue code as error proof as possible. If it isn't possible to make it so error proof that exceptions are vanishingly rare, then rather than beginning a nest of rescue blocks inside of rescue blocks, call another method that handles its own exceptions, e.g.:
def foo
1/0
rescue
complicated_foo_error_handler
end
private
def complicated_foo_error_handler
# handle foo errors
rescue
complicated_complicated_foo_error_handler_error_handler
end
def complicated_complicated_foo_error_handler_error_handler
# handle complicated_foo_error_handler errors
rescue
STDERR.puts 'I give up!'
exit false
end
Upvotes: 4