我原以为typeof(...)
会给我一个确切的类,但在抢救异常typeof(MyCustomException)
时只返回Exception
class A < Exception; end
class B < A; end
begin
raise B.new
rescue e
puts typeof(e) # => Exception
end
puts typeof(B.new)
按预期返回B
答案 0 :(得分:1)
根据我在此处创建的问题的https://github.com/bararchy: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
所以是啊e.class
返回B
答案 1 :(得分:1)
rescue e
不限制此救援块处理的异常类型。因此e
可以是任何例外类型。
如果您只想处理B
类型的异常,则应添加类型限制rescue e : B
。然后,typeof(e)
将为B
。