What does the fail keyword do in Ruby?
I am learning Ruby and encountered the fail
keyword. What does it mean?
if password.length < 8
fail "Password too short"
end
unless username
fail "No user name set"
end
Solution 1:
In Ruby, fail
is synonymous with raise
. The fail
keyword is a method of the Kernel
module which is included by the class Object
. The fail
method raises a runtime error just like the raise
keyword.
The fail
method has three overloads:
fail
: raises aRuntimeError
without an error message.-
fail(string)
: raises aRuntimeError
with the string argument as an error message:fail "Failed to open file"
-
fail(exception [, string [, array]])
: raises an exception of classexception
(first argument) with an optional error message (second argument) and callback information (third argument).Example: Assume you define a function which should fail if given a bad argument. It is better to raise an
ArgumentError
and not aRuntimeError
:fail ArgumentError, "Illegal String"
Another Example: You can pass the whole backtrace to the
fail
method so you can access the trace inside therescue
block:fail ArgumentError, "Illegal String", caller
caller
is a Kernel method which returns the backtrace as an array of strings in the formfile:line: in 'method'
.
With no arguments, raises the exception in $! or raises a RuntimeError if $! is nil. 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). The optional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught by the rescue clause of begin...end blocks.
Source: Ruby Documentation on the Kernel Module.
Solution 2:
Rubocop says about usage of both words;
'Use
fail
instead ofraise
to signal exceptions.''Use
raise
instead offail
to rethrow exceptions.'
Here is an example.
def sample
fail 'something wrong' unless success?
rescue => e
logger.error e
raise
end
Solution 3:
fail
== raise
In other words, fail
is just a popular alias for raise
error-raising method. Usage:
fail ArgumentError, "Don't argue with me!"
Solution 4:
www.ruby-doc.org is your friend. When I googled rubydoc fail
"Kernel" was the first hit. My advice is, when in doubt, go to the definitive source for definitional stuff like this.