views:

215

answers:

3

I almost feel embarrassed to ask, but I always struggle with how to organize exception definitions. The three ways I've done this before are:

  • Use the file-per-class rule. I'm not crazy about this because it either clutters up my directory structure and namespaces. I could organize them into subdirectories and segment namespaces for them, but I don't really like that, and that's not how the standard libraries usually do it.
  • put the definitions in a file containing the related class(es). I don't really like this either because then exception definitions are scattered about and may be hard to find without the aid of a code navigation tool.
  • One file with all the exception definitions for a namespace or "package" of related classes. This is kind of a compromise between the above two, but it may leave situations in which it's hard to tell which exceptions "belong" to a particular group of classes or set of functionality.

I don't really like any of the above, but is there a sort of best-practice that I haven't picked up on that would be better?

Edit: Interesting. From the "Programming Microsoft Visual C# 2008: The Language", Donis suggests:

For convenience and maintainability, deploy application exceptions as a group in a separate assembly. (p. 426

I wonder why?

+2  A: 

I tend to place the Exceptions one per file in the same package as the objects which produce them, in individual files. This is the paradigm used by the Java APIs and the .Net libraries, so most people are at least familiar with the organization of the objects at that point.

Modern IDE's do a good enough job of keeping track of the files in a directory that the benefits of having the class in a file of the same name tend out outweigh the value of having fewer files.

Adam N
+2  A: 

In C++, I've always defined classes that I will use as exceptions in the same namespace as the classes which throw them, co-locating them in the same header. For general purpose exceptions, that will be shared between classes, I use a single header to group them together, along with other utility functions and classes.

I don't believe there's any one correct way of doing things in this regard; it's whatever works for you in your context.

Jason Etheridge
+1  A: 

I use the following approaches:

  • Exception class in a separate file: when it's generic and can be thrown by more than one class
  • Exception class together with the class throwing it: when there is only one such class. This makes sense because the exception is part of that class' interface

A variant on the latter is making the exception a member of the throwing class. I used to do that but found it cumbersome.

Lev