Crystal 引发异常 class

Crystal get raised Exception's class

我原以为 typeof(...) 会给我确切的 class,但在拯救异常时 typeof(MyCustomException) 只是 returns Exception

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

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

puts typeof(B.new) returns B 符合预期

根据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

是的 e.class returns B

rescue e 不限制此救援块处理的异常类型。因此 e 可以是任何异常类型。

如果您只想处理B类型的异常,您应该添加类型限制rescue e : B。然后,typeof(e) 将是 B.