tpei
tpei

Reputation: 681

Crystal get raised Exception's class

I was expecting that typeof(...) would give me the exact class, but when rescuing an Exception typeof(MyCustomException) just returns Exception

class A < Exception; end
class B < A; end

begin
  raise B.new
rescue e
  puts typeof(e) # => Exception
end

Whereas puts typeof(B.new) returns B as expected

Upvotes: 0

Views: 69

Answers (2)

Johannes M&#252;ller
Johannes M&#252;ller

Reputation: 5661

rescue e does not restrict the type of exception handled by this rescue block. Therefor e can be any exception type.

If you only want to handle exceptions of type B, you should add a type restriction rescue e : B. Then, typeof(e) will be B.

Upvotes: 1

tpei
tpei

Reputation: 681

As per https://github.com/bararchy on the issue I created here: https://github.com/crystal-lang/crystal/issues/4597

I think that typeof is indeed Exception, but .class will give you what you want , I could be mistaken but I think that is intended

So yeah e.class returns B

Upvotes: 1

Related Questions