A gem for defining ruby exceptions
Exceptions in ruby are defined by subclassing off of a standard exception and then using raise to invoke them. Messaging is typically separate from the class definition which isn’t very DRY when invoking raise with a second String argument multiple times. The define_exception gem provides a succinct manner in which exceptions can be defined much like read/write attributes in your class using attr_accessor. It also makes it trivial to define a default message so that in most cases the second argument to raise is not necessary.
Comments
The problem I see with this is the lack of subclassing. Maybe a better approach would be something like:
class MyClass MyException = ArgumentError.factory(‘my new message’) end
If you look at the code under the hood you will see that this is a class method that performs the subclassing off of RuntimeError automatically setting up the default message for the exception.
I understand, but you don’t always want a subclass of RuntimeError. Sometimes you need a subclass of another type of error.
Got it. I’ll add an optional argument which will allow for subclassing off another Exception class.
Post a comment