Search code examples
rubyerror-handlingrescue

what does "rescue false" mean inside if condition in ruby


I am ruby newbie and have one question.

if (new_account.save rescue false)
   # when account save success
else
   # when account save has error
end

I am not sure what rescue false means in this code. Thanks


Solution

  • A one-line rescue is syntactic sugar

    foo.bar rescue false
    # same as
    begin
      foo.bar
    rescue
      false
    end
    

    So your code is pretty much the same as this

    result = nil
    begin
      result = new_account.save
    rescue
      result = false
    end
    
    if result
      # when account save success
    else
      # when account save has error
    end
    

    The rescue false means that an exception thrown inside new_account.save is treated the same as it returning false. In my opinion, this is bad design. new_account is clearly designed to have two different failure cases, but the calling code ignores it. This code is extremely likely to hide actual bugs occurring inside the saving method.