Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a handled RuntimeError in Ruby

Tags:

exception

ruby

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
like image 393
Lorin Hochstein Avatar asked Jul 20 '26 14:07

Lorin Hochstein


1 Answers

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.

like image 165
Arup Rakshit Avatar answered Jul 22 '26 07:07

Arup Rakshit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!