2014-10-23

When generic exceptions are useful

So this is not about catching the base exception but something kind of like using tuples; having an exception template using generics.

So an interesting pattern I've seen is the use of a template based exception class defined something like TypedException<T>.  The benefit from this pattern is that with one single definition you can create a variety of exceptions. And unlike tuples you still have easy to understand code as long as you use descriptive types together with the TypedException.

There is however one thing to be careful of. Since this approach is so convenient and still produces maintainable code there can be a tendency to force the use of this pattern even when the "standard" approach to exceptions is more suitable. And if you are not careful your team might even produce a number of helpers for this generic exception forcing you to use it more or less against your will in order to reuse other code.

So have you been in contact with this pattern and what did you think?

No comments:

Post a Comment