Ruby offers two possibilities to cause an exception programmatically: raise
and fail
, both being Kernel
methods. According to the documents, they are absolutely equivalent.
Out of a habit, I used only raise
so far. Now I found several recommendations (for example here), to use raise
for exceptions to be caught, and fail
for serious errors which are not meant to be handled.
But does it really make sense? When you are writing a class or module, and cause a problem deep inside, which you signal by fail
, your programming colleagues who are reviewing the code, might happily understand your intentions, but the person who is using my code will most likely not look at my code and has no way of knowing, whether the exception was caused by a raise
or by fail
. Hence, my careful usage of raise
or fail
can't have any influence on his decision, whether she should or should not handle it.
Could someone see flaws in my arguments? Or are there other criteria, which might me want to use fail
instead of raise
?
I once had a conversation with Jim Weirich about this very thing, I have since always used
fail
when my method is explicitly failing for some reason andraise
to re-thrown exceptions.Here is a post with a message from Jim (almost verbatim to what he said to me in person): http://www.virtuouscode.com/2014/05/21/jim-weirich-on-exceptions/
Here is the relevant text from the post, a quote attributed to Jim:
I know that there are many style guides that do not agree (the style guide used by RoboCop, for example). I don't care. Jim convinced me.
This is not what the official style guide or the link you provided say on the matter.
What is meant here is use
raise
only inrescue
blocks. Aka usefail
when you want to say something is failing and useraise
when rethrowing an exception.As for the "does it matter" part - it is not one of the most hardcore strictly followed rules, but you could make the same argument for any convention. You should follow in that order:
Ideally, the three should be the same.
Update: As of this PR (December 2015), the convention is to always use
raise
.