Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising an exception: use instance or class?

I have seen Ruby code that raises exceptions using a class:

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

Other code uses an instance:

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

Both of these are rescued the same way. Is there any reason to use an instance vs a class?

like image 651
Nathan Long Avatar asked Mar 09 '12 17:03

Nathan Long


People also ask

Which is used to raised the exception?

The raise keyword is used to raise an exception. You can define what kind of error to raise, and the text to print to the user.

How do you raise an exception?

If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.

What is meant by raising an exception?

Raising an exception is a technique for interrupting the normal flow of execution in a program, signaling that some exceptional circumstance has arisen, and returning directly to an enclosing part of the program that was designated to react to that circumstance.

What is the use of raising an exception in Python?

raise allows you to throw an exception at any time. assert enables you to verify if a certain condition is met and throw an exception if it isn't. In the try clause, all statements are executed until an exception is encountered. except is used to catch and handle the exception(s) that are encountered in the try clause.


1 Answers

It makes no difference; the exception class will be instiantiated in either case.

If you provide a string, either as the argument to new or as the second argument to raise, it be passed to initialize and will become the exception instance's .message.

For example:

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 the first raise above, you'll see that:

  • In both cases, initialize is called.
  • In both cases, the exception class is GoatException, not class as it would be if we were rescuing the exception class itself.
like image 94
Nathan Long Avatar answered Sep 20 '22 20:09

Nathan Long