2012-03-09 40 views
4

我見過的Ruby代碼,提高使用類異常:引發異常:使用實例還是類?

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

其他代碼使用的實例:

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

上述這些問題都救出了同樣的方式。是否有任何理由使用實例與類?

回答

9

這沒有什麼區別;在任何一種情況下都會對異常類進行檢查。

如果你提供一個字符串,無論是作爲參數傳遞給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因爲這將是如果我們營救異常類本身。