Coding
Advertisements
Related Guides
| |
Null pointer exceptions are runtime errors that are generated when you try to use an object that hasn't been initialized. This is one of the most common types of exceptions in many programing languages. Fortunately, it is also one of the easiest to deal with.
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.|
Type | | Definition | Runtime errors that are generated when code attempts to use an uninitialized object. | Related Concepts | |
Coding
This is the complete list of articles we have written about coding.
If you enjoyed this page, please consider bookmarking Simplicable.
© 2010-2023 Simplicable. All Rights Reserved. Reproduction of materials found on this site, in any form, without explicit permission is prohibited.
View credits & copyrights or citation information for this page.
|