Use Identical Exception Handlers

In a well structured program exception handlers are rare.

They are placed high in the call-chain and usually either delegate the decision making to the end user or they TranslateExceptions to some other form for use by another sub-system.

Usually each sub-system has several entry points that must be guarded by exception handlers. These handlers all perform the same service for the sub-system.

Therefore:

Devise a strategy for handling each type of exception (preferably with most types handled in a single, uniform, way) and then implement that strategy in every handler throughout the system without regard to the types of exception that a particular handler can be expected to be exposed to.

This expresses the nature of exception handlers accurately: each of them is an instance of one conceptual piece of code. The only reason that they are duplicated at all is because their services are needed in separate locations and the mechanics of the language contain no abstractions that can be used to generalize the duplication.

By making all handlers identical (even though some will expect to handle different specific errors) we allow ourselves to focus on the task of handling errors in a uniform way.

On the special occasions when an error needs to be handled differently we write a different handler, of course, but on that occasion the intent to handle the error specially is clear because the handler is different from all of the other handlers for that sub-system.


This does seem a bit dangerous... slippery slope and all...

I understand that the words try and catch obviously need to be repeated, but what stops you from putting the repeated code in a method and calling it? Place the generic code in a subclass of Exception (including the 'throw' command), and call it... if the exception wants to be thrown, it can throw itself, if not, assume it managed to get things sorted out (btw, I'm just trying this technique (pattern?) on my current project, I guess we'll see how it turns out)

 --WilliamUnderwood


It's not possible in general to handle errors in a uniform way. What is, or is not, an error, depends critically on the context. Is it an error if the key you're trying to look up doesn't exist? Not if you're prepared to fall back on a default.


CategoryException


EditText of this page (last edited May 18, 2011) or FindPage with title or text search