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:
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?
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.
I use the following approaches:
A variant on the latter is making the exception a member of the throwing class. I used to do that but found it cumbersome.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With