Search code examples
rubyrescue

Catch-all rescue


In Ruby/Rails, is there a "catch-all" rescue statement that also allows for more specific rescue possibilities? I tried

begin
  # something
rescue URI::InvalidURIError
  # do something
rescue SocketError
  # do something else
rescue 
  # do yet another thing
end

It turns out that even when there's URI::InvalidURIError or SocketError, it goes into the last rescue (i.e. it executes do yet another thing.) I want it to do something, or do something else, respectively.


Solution

  • require 'uri'
    require 'socket'
    
    Errors = [URI::InvalidURIError, SocketError]
    a = lambda { |e=nil|
                 begin
                   raise e unless e.nil? 
                 rescue URI::InvalidURIError
                   puts "alligator"
                 rescue SocketError
                   puts "crocodile"
                 rescue
                   puts "vulture"
                 else
                   puts "rhino"
                 end }
    

    Now try

    a.( Errors[ 0 ] )
    a.( Errors[ 1 ] )
    a.call
    

    It will behave exactly as you need. If your code above doesn't work, then something else is going on in your program than you think.