x = StandardError.new(:hello)
y = StandardError.new(:hello)
x == y # => true
x === y # => true
begin
raise x
rescue x
puts "ok" # gets printed
end
begin
raise x
rescue y
puts "ok" # doesn't get printed
end
Why isn't the second "ok" printed? I can't figure it out. I've read here that ruby uses the === operator to match exceptions to rescue clauses, but that's ostensibly not the case.
I'm using Ruby 1.9.3
EDIT: So it seems like that after doing raise x, x == y and x === y no longer hold. It seems to because x and y no longer have the same backtrace.
I think that's a bug, or rather an underspecification of Ruby 1.9. Note that Ruby 2.0 raises a
TypeError: class or module required for rescue clause
on lines 8 and 14.
Note that the raise doesn't necessarily do what you think it does, either. When you raise an object, you don't actually raise that object, you raise a new object which is constructed from the object you passed according to these simple rules:
exception, call exception on the object and raise the return valueException, call new and raise the return valueException
So, you are not actually raising x, you are raising x.exception. According to the documentation of Exception#exception x.exception is x, though.
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