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?
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.
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.
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.
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.
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:
initialize
is called.GoatException
, not class
as it would be if we were rescuing the exception class itself.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With