我见过使用类引发异常的 Ruby 代码:
raise GoatException, "Maximum of 3 goats per bumper car."
其他代码使用实例:
raise GoatException.new "No leotard found suitable for goat."
这两个都是以同样的方式获救的。是否有理由使用实例而不是类?
最佳答案
没有区别;在任何一种情况下都会实例化异常类。
如果您提供一个字符串,作为 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
,如果我们要拯救异常类本身的话。
关于ruby - 引发异常 : use instance or class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9638475/