In Ruby, fail is synonymous with raise . The fail keyword is the Kernel module method, which is part of the Object class. The fail method raises a run-time error, as raise keyword.
The fail method has three overloads:
fail : raises a RuntimeError without an error message.
fail(string) : raises a RuntimeError with a string argument as an error message:
fail "Failed to open file"
fail(exception [, string [, array]]) : an exception is thrown in the exception class (first argument) with an optional error message (second argument) and callback information (third argument).
Example. Suppose you define a function that should fail if an invalid argument is given. It is better to raise an ArgumentError rather than a RuntimeError :
fail ArgumentError, "Illegal String"
Another example: you can pass the entire backtrace fail method so that you can access the trace inside the rescue block:
fail ArgumentError, "Illegal String", caller
caller is a Kernel method that returns a backtrace as an array of strings in the form file:line: in 'method' .
Without arguments, an exception occurs in $! or creates a RuntimeError if $! equal to zero. With one argument String, a RuntimeError occurs with the string as a message. Otherwise, the first parameter must be the name of the Exception class (or an object that returns an exception object when sending an exception message). An additional second parameter sets the message associated with the exception, and the third parameter is an array of callback information. Exceptions are caught using the rescue begin ... end blocks command.
Source: Ruby Documentation on the kernel module .
crazybob Sep 15 '13 at 11:20 2013-09-15 11:20
source share