Throw an exception: use an instance or class?

I saw Ruby code that throws exceptions using a class:

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

Another code uses an instance:

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

Both of them are saved equally. Is there a reason to use an instance for a class?

+4
source share
1 answer

It does not matter; the exception class will be initialized anyway.

If you provide a string, either as a new argument, or as a second argument to raise , it is passed to initialize and will become an instance of a .message exception.

For instance:

 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 

If you comment on the first raise above, you will see that:

  • In both cases, initialize is called.
  • In both cases, the exception class is GoatException , and not the class , as it would be if we saved the exception class itself.
+9
source

Source: https://habr.com/ru/post/1400626/


All Articles