Designing exception class hierarchies
In general, if you are writing a library and raising an exception in it, it is useful to have a custom exception subclass that you use. Let's say you are passing an object to your method, and the object has to be allowed, or an exception should be raised. Ruby allows you to do this by using the following code:
def foo(bar) unless allowed?(bar) raise "bad bar: #{bar.inspect}" end end
However, this is a bad approach, as it raises RuntimeError
. In general, it is better to raise an exception class related to your library, since that allows users of your library to handle the exception differently from exceptions in other libraries. So if you have a library named Foo
, it's common to have an exception class named something like Foo::Error
that you can use for exceptions raised by the library. The following code demonstrates this:
module Foo class Error < StandardError...