Ruby错误“ inheritance of the message attribute”是怎么回事?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (22)

我似乎找不到很多关于自定义异常类的信息

我只知道这些

class MyCustomError < StandardError
end
raise MyCustomError, "A message"
rescue MyCustomError => e
  puts e.message # => "A message"

以下内容正确吗:

class MyCustomError < StandardError
  attr_reader :object
  def initialize(message, object)
    super(message)
    @object = object
  end
end:
raise MyCustomError.new(anObject), "A message"
rescue MyCustomError => e
  puts e.message # => "A message"
  puts e.object # => anObject

提问于
用户回答回答于

raise已经设置了消息,因此不必将其传递给构造函数:

class MyCustomError < StandardError
  attr_reader :object

  def initialize(object)
    @object = object
  end
end

begin
  raise MyCustomError.new("an object"), "a message"
rescue MyCustomError => e
  puts e.message # => "a message"
  puts e.object # => "an object"
end

用户回答回答于

你的想法是正确的,但你的说法不对。应该是

raise MyCustomError.new(an_object, "A message")

扫码关注云+社区