FAQ 9.11 How should exception classes be named?

Name the error, not the thrower.

The server should throw an exception whose class name describes the error that occurred rather than describing the code that detected the exception. In other words, the type of the exception object should embody the meaning of what went wrong.

For example, if a List class is asked to remove an element and the List is empty, the List should throw an exception such as EmptyContainer rather than an exception such as ListError.

The purpose of this advice is to enhance information hiding. For example, suppose class List is used to build class Queue; the EmptyContainer exception might be meaningful to users of Queue.

However, if List threw a ListError, users of Queue would become aware of the internal implementation details of Queue (that is, it uses a List). Since this could introduce a ripple effect (for example if the Queue found it more efficient to use a vector than to use a List, all the users of Queue might have to update their catch(ListError) blocks), the author of the Queue class would probably want to catch all these ListError exceptions and repackage them as something that doesn't expose the List detail, then throw that more generic object. So either the author of Queue has extra work to do or the users of Queue end up knowing too much about how Queue is implemented. Clearly it would have been easier if List had thrown something generic such as ContainerIsEmpty.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net