April 17, 2009

How do you design exception handling?

A while ago I took over an internal tool with the task of turning it into a reusable component and enhancing it with new features. Given that it had been conceived as a command-line tool to be used only by the other developers in the team, the author of the code had a very simple exception handling policy: let'em all bubble up until they splash at the console - the user will know what to do.

So I rolled my sleeves up and started writing exception handling, and I was struck at how much grief it gave me. I knew the guidelines, I knew the recommendations, I knew the practices, but when I got down to the nitty gritty, it still felt on-the-fly, I still had the feeling that I wasn't doing it right, that it wasn't robust enough.

Last week I attended a 4-day training session on Design Patterns with Alan Shalloway, main author of Design patterns explained. The ~20 hours of training were very good, but as they were drawing to an end, I realised that not once had he mentioned exception and error handling. Alan did seem intimately familiar with the literature on design patterns and object orientation however, so I thought he would be the perfect person to ask: "How can I learn about designing exception handling? Has anybody written about that?".

But when he answered that he didn't quite know, I started thinking that exception handling design is an undeserving neglected topic. And the more I thought about, the more evidence I found. Think about it, how many times did you write a design document that included a section on exception handling? How many times did you design an interface and put serious thought into defining a set of exceptions for implementors to throw in a consistent manner?

How about it, then? Have you learned or worked out any design patterns for exception handling? I mean something more cohesive than your usual set of "do this / don't do that" guidelines, something reusable at design time rather than at implementation time. I'd very much like to hear from you on this subject.

3 comments:

Emmanuel2.0 said...

I guess u are right, exception handling is quite a task in huge apps.

Ciobanu Jescu Cristian said...

I guess one should make a very good design of the application, and then try to test each function in every module, and create exception handling chains if functions call one another.

Vlad said...

That's precisely the problem. You need a consistent way of handling exceptions across a multitude of function call chains and most probably across several aplication layers. The exceptions a library or a component or an application tier may throw are very much part of their API. And you want your APIs to be cohesive, easy to use and so on.

The Enterprise Library Exception Handling Application Block is worth a try and I'd be interested in hearing about similar libraries.