From: Joe Van Dyk Date: 2005-09-02T05:18:52+09:00 Subject: Re: custom exceptions On 8/30/05, Eric Hodel wrote: > On 30 Aug 2005, at 10:52, Joe Van Dyk wrote: > > > When should you define your own exceptions? Any rules of thumb? > > I define custom exceptions when I need to differentiate them from the > built-in exceptions. > > > I'm writing an application that runs on a computer and listens for > > requests to start, kill, and view log files for other applications on > > that computer. Say I get a request to start an application on that > > computer and the requested executable doesn't exist. Should I throw a > > custom exception then? Or, say an application dies unexpectedly. > > What should I use for an exception then? > > Sometimes an exception with a message is enough. Other times I need > to know the difference between two RuntimeErrors with different > messages. > > I create my own exceptions for the second case because rescue > FooError is easier than reading exception messages. Should the custom exception be in its own class? Or in a module? Say I have the following class class NodeManager def start_application args end end There are a few different ways start_application could fail: - bad arguments - user attempted to start the same application twice (which is an error for us) - not enough resources available I want to distinguish between those different reasons. So, would I want to have something like this: module JoesExceptions # figure out some name class BadArgumentsForApplication < Exception end class ApplicationStartedTwice < Exception end class NotEnoughResourcesForApplication < Exception end end And then, in start_application: def start_application args # if arguments are bad raise BadArgumentsForApplication # and so on end