Comparing a handled RuntimeError in Ruby
exception, ruby
Solution
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 `true` if exc and obj share same class, messages, and backtrace.
Now, in your case `e` and `err` has 2 different backtrace, thus it returns `false`.
Problem
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 ```