Search code examples
rubyabortraise

Better to abort() or raise() on argument error in Ruby?


I'm writing a command-line utility in Ruby and coding the logic that checks whether the combination of arguments is valid. If I find an error, what is the advantage of raising an ArgumentError vs. calling abort() on the spot if I don't intend to recover? In general, when is it advisable to raise an exception instead of aborting if there are no plans to attempt recovery? I'd assume that the exception route is advisable is some kind of graceful shut-down is needed instead of simply dropping back to the command line.


Solution

  • Always, always raise exceptions in preference to aborting. Aborting is ugly and really a last-resort sort of hack that you use if you really cannot meaningfully continue.

    You can continue after an ArgumentError: you can tell the user what the right syntax is and you can print a help message. Or, maybe later on you reuse the argument parser in another project, which can handle the errors. (Indeed, a common idiom is to call the argument parser within an exception block, and print out the help message if the argument parser raises an error).

    In any case, the default behaviour of ArgumentError is similar to abort, but you can do a lot more with it. You should therefore go with this more flexible solution, in my opinion.