引发异常:使用实例或类?

时间:2012-03-09 17:33:10

标签: ruby exception exception-handling

我见过使用类引发异常的Ruby代码:

raise GoatException,    "Maximum of 3 goats per bumper car."

其他代码使用实例:

raise GoatException.new "No leotard found suitable for goat."

这两个都以同样的方式获救。有没有理由使用实例与类?

1 个答案:

答案 0 :(得分:11)

没有区别;在任何一种情况下,异常类都将被公开。

如果你提供一个字符串,作为new的参数或作为raise的第二个参数,它将被传递给initialize并将成为异常实例的.message }。

例如:

class GoatException < StandardError
  def initialize(message)
    puts "initializing with message: #{message}"
    super
  end
end

begin
  raise GoatException.new "Goats do not enjoy origami." #--|
                                                        #  | Equivilents
  raise GoatException,    "Goats do not enjoy origami." #--|
rescue Exception => e
  puts "Goat exception! The class is '#{e.class}'. Message is '#{e.message}'"
end

如果您对上面的第一个raise发表评论,您会看到:

  • 在这两种情况下,都会调用initialize
  • 在这两种情况下,异常类都是GoatException,而不是class,就像我们正在拯救异常类本身一样。
相关问题