When I handle a Ruby exception and compare it to an exception object that I construct, it evaluates to false. Why is this so?
To give a specific example, why does this print false?
begin
raise "An error happened"
rescue => e
end
err = RuntimeError.new("An error happened")
puts e == err
Here is the answer :
begin
raise "An error happened"
rescue => e
end
err = RuntimeError.new("An error happened")
[e.backtrace,err.backtrace] # => [["-:2:in `<main>'"], nil]
[e.class,err.class] # => [RuntimeError, RuntimeError]
[e.message,err.message] # => ["An error happened", "An error happened"]
puts e == err
# >> false
Documentation of #== is saying :
Equality—If obj is not an Exception, returns false. Otherwise, returns
trueif exc and obj share same class, messages, and backtrace.
Now, in your case e and err has 2 different backtrace, thus it returns false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With