December 07, 2008







Each library should have a superclass for its exceptions.


Create a new subclass for each distinct outcome.


Remember that exceptions can hold data.


What other tips and tricks would you suggest?


  1. Exceptions should also be self-describing and logged, using whatever mechanism your language supports (toString(), ex.what(), etc.). It's frustrating to see an exception thrown in a production environment which is hard to produce but gives you nothing more than some very basic information, like the exception class name.

    Any exception should give as much information as possible. And, since you noted exceptions can hold data, this should usually be possible.

  2. In my opinion exceptions should not be used to pass information except that which is necessary to identify the immediate cause of the exception, e.g., stack trace plus whatever variables had an invalid value etc. Exceptions should not be seen as a pipe for passing extra information, because if that information really *needs* to travel to some destination there should have been an explicit code path for it to travel. One serious potential side effect of extra info in an exception is that if the exception is NOT handled the way you expect, the info in the exception may be exposed to the user, which may be a security risk or privacy issue.

  3. In my experience, programmers tend to rely on exceptions to alleviate themselves of the responsibility of writing robust code. For example, a square root function which doesn't bother to check if the input it was passed is a negative number.

    Ideally, programmers should anticipate all the various ways in which their code can be misused, and handle them as gracefully as possible. Doing so can add more functionality in the code and provide the user with a more productive experience.

  4. I agree with Tom that having language-level support for exceptions is not a substitute for writing rigorous, defensive code. On the contrary, I think using exceptions (i.e., throwing and catching them appropriately) is a major boon to writing robust and correct code. Once a programmer has "anticipate[d] all the various ways in which their code can be misused", the most graceful thing to do is raise a well-choosen exception to allow a component with more context of the actual user intent to gracefully clean up and deal with the problem in a friendly way.

  5. Oops... I meant: "...the most graceful thing to do is *often to* raise a..."