PreventionBefore you use any object test if it is null if there is any possibility that it is uninitialized. If it is null, do something intelligent given the context. For example, if you query a database and the result is null, this may indicate an empty result set. As such, you might display a meaningful message to users that no results were found.
TroubleshootingA null pointer exception indicates an object was used before being initialized. Troubleshooting such problems involves looking at the line where the error occurred to identify where the code uses an object without testing if it is null.
ThrowingA null pointer exception indicates that code attempted to access an object that points at nothing. Generally speaking, it is a poor practice to throw your own null pointer exception because this has little global meaning. For example, if your code can't connect to a database, it is better to throw an exception that indicates this fact as opposed to throwing a null pointer exception. If a required parameter is null, throwing an exception such as "IllegalArgumentException" is more helpful.
HandlingWhen null pointer exceptions do occur it is common to handle them by throwing them such that they result in some type of error to the user. As they are an extremely common and generic type of exception, it is difficult to make assumptions about what they mean. For example, it would typically look sloppy to implement business logic to handle a null pointer exception. In some cases, a null pointer exception is handled with an empty catch or a log entry. Generally speaking, it is better to prevent the exception in the first place as this makes your code more clear to others.
|Overview: Null Pointer Exceptions
Runtime errors that are generated when code attempts to use an uninitialized object.