Written January 13, 2015. Tagged Ruby, Exceptions.
In Ruby, when should you define your own exception class and when shouldn't you bother?
Defining your own exception class looks something like
class UnparsableValueError < StandardError; end
def parse(value)
raise UnparsableValueError unless value.start_with?("number:")
actually_parse(value)
end
Raising a generic RuntimeError
from a string looks like
def parse(value)
raise "Couldn't parse: #{value.inspect}" unless value.start_with?("number:")
actually_parse(value)
end
This is how I decide:
You could raise a custom class with a message string, of course, to get the clear phrasing, but that still means adding a class you don't need.
In Practical Object Oriented Design in Ruby, Sandi Metz says:
When the future cost of doing nothing is the same as the current cost, postpone the decision. Make the decision only when you must with the information you have at that time.
That's why I don't introduce exception classes until I need them.