Reputation: 275
Consider the two following ways to raise an exception -
class ExampleError < StandardError; end
raise ExampleError.new
raise ExampleError
In the first way, an instance of ExampleError
is given to the method raise
. The raise
method can accept an Exception
parameter and everything is clear.
In the second way a Class
instance is given to the method, yet this still works.
Due to the fact that raise
can accept String
, was there implicit conversion of the parameter from Class
to String
?
Thank you
Upvotes: 1
Views: 300
Reputation: 230396
No, it does not get converted to String
. In fact, your assumption was wrong. raise
doesn't want an instance of some exception class. It would rather have the exception class itself. See documentation for Kernel#raise:
... With a single String argument, raises a RuntimeError with the string as a message. Otherwise, the first parameter should be the name of an Exception class (or an object that returns an Exception object when sent an exception message). ...
So, you can pass anything to raise
, as long as it's a string or has exception
method. Both your variants pass here:
class ExampleError < StandardError; end
ExampleError.exception # => #<ExampleError: ExampleError>
ExampleError.new.exception # => #<ExampleError: ExampleError>
Upvotes: 4