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

Nat*_*ong 6 ruby exception-handling exception

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

raise GoatException,    "Maximum of 3 goats per bumper car."
Run Code Online (Sandbox Code Playgroud)

其他代码使用实例:

raise GoatException.new "No leotard found suitable for goat."
Run Code Online (Sandbox Code Playgroud)

这两种都以同样的方式获救.是否有任何理由使用实例与类?

Nat*_*ong 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
Run Code Online (Sandbox Code Playgroud)

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

  • 在这两种情况下,都initialize被称为.
  • 在这两种情况下,异常类都不是GoatException,class如果我们正在拯救异常类本身.