First page Back Continue Last page Summary Graphics

The code between


Notes:

The difficulty in writing exception safe code isn't in writing the code that throws an exception, or in writing the code that catches the exception to handle it. There are many sources that cover these basics. I'm going to address the greater challenge of writing the code that lies between the two.
Imagine for a moment the call stack of a running program, a method a() has called another method b(), b() has called c(), and so on, until we reach x(); x() encounters a problem and throws an exception. This exception causes the stack to unwind, executing the code in finally (or catch) blocks, until the exception is dealt with by a().
I'm not going to spend any time on how to write methods a() or x(). I'm sure that the author of x() has a perfectly good reason for throwing an exception (running out of memory, disk storage, or whatever) and that the author of a() knows just what to do about it (display: "Sorry, please upgrade your computer and try again!").
The difficult problem is to write all the intervening methods in a way that ensures that something sensible happens as a result of this process. If we can achieve this we have "exception safe" code. Of course, that begs the question "what is something sensible?" To answer this let us consider a typical method m() in the middle of the call stack. How should m() behave?
Well, if m() were to handle the exception it might be reasonable for it to complete its task by another method (a different algorithm, or returning a "failed" status code). However, we are assuming the exception won't be handled until we reach a().