Friday, March 18, 2011

Never take notice of an error that you don't know how to handle

This is in general a good principle, but in specific cases it is a good idea to intercept it. The special case is when the error occurs at a very low level (i.e. a null pointer exception) and thus there is not enough context information to make sense of the error.

When debugging, it isn't an issue because you have access to the call stack and can figure out the context from there. If, however, the error is generated for a user, and the user provides the information to support, then there won't be enough information to figure out the error, at least not easily.

In this case (or if you are a developer and are anticipating this case happening in the future, where the user might be QA) it is often helpful to catch the error, add some context information, and rethrow the exception. Or, you could check for the error that might cause the exception, and throw an exceptioin yourself instead of calling the routine that might generate the exception.

For example, usinng a variable

Class1 c = complicatedCreationMethod();



Now, method1 will fail if c is null. If there is any possibility that complicatedCreationMethod() might return null, you may want to check for this and throw an exception rather than simply letting the null pointer exception percolate to the top of the error handlers.

No comments:

Post a Comment