Best practice: Using system supplied or custom exceptions for error conditions in ruby?
exception, ruby
Solution
I believe the best practice is to raise your own custom error, namespaced in a module. All of your specific exception classes should inherit from one namespaced exception that inherits from StandardError. So for your case:
module MyApp
class Error < StandardError; end
class ArgumentError < Error; end
end
and raise MyApp::ArgumentError when the user provides bad arguments. That way it differentiates from an argument error in your code. And you can rescue any uncaught exception from your app at a high level with MyApp::Error.
You should also check out Thor. It can handle most of the user argument stuff for you. You can look at Bundler for a good cli usage example.
Problem
Writing a rather simple command line tool in ruby I need to report meaningful messages on errors in the command line arguments, or for that matter other error conditions in the program. (Input file not found, invalid format of input etc) For now I just raise ArgumentError with a sensible description when detecting errors in the argument list. Is this good practice, or do I risk hiding programming errors as well with this approach? In other words, are the system defined exceptions in ruby meant for application usage, or should we always create our own exceptions for reporting non-system errors? Edit: As an example, ruby raises ArgumentError if I call a method with the wrong number of arguments. This is a programming error that I want to be told about with stack traces and all. However when input to my program is incorrect I may want to give a brief message to the user, or even ignore it silently. This suggests to me that ArgumentError is not suitable for the applications own use.