ApexNullPointerExceptionRule identifies Apex operations that dereference null objects and throw NullPointerExceptions. NullPointerExceptions generally indicate underlying problems in your code to address.
Definition
-
Source
- :
@AuraEnabled-annotated methods.@InvocableMethod-annotated methods.@NamespaceAccessible-annotated methods.@RemoteAction-annotated methods. Any method returning aPageReferenceobject.public-scoped methods on Visualforce Controllers.global-scoped methods on any class.Messaging.InboundEmailResult handleInboundEmail()methods on implementations ofMessaging.InboundEmailHandler. Any method targeted during invocation.
- :
-
Sink
- : Any object dereference is a potential sink because object dereferences are the places where a null pointer exception can be thrown. Example:
x.someMethod()|
- : Any object dereference is a potential sink because object dereferences are the places where a null pointer exception can be thrown. Example:
-
Sanitizer
- : Non-null initialization of variables and null checks before accessing. Examples:
String s = 'abcde';,if (s != null) {.
- : Non-null initialization of variables and null checks before accessing. Examples:
Interpreting Results
Match any violation message that you receive with this case to understand more about the violation.
Common Case
ApexNullPointerExceptionRule identifies Apex operations with a high likelihood of throwing a NullPointerException
The operation dereferences a null object and throws a NullPointerException. Review your code and add a null check.
Examples
In these examples, Apex Runtime throws a System.NullPointerException at the place where an operation is performed on a null object. The Graph Engine ApexNullPointerException rule preemptively identifies these operations.
public void example1() {
Object myStr = null;
System.debug(myStr.toLowerCase());
// throws System.NullPointerException
// since method is invoked on null object.
}
public void example2(String myStr) {
if (myStr == null) {
// The following line throws System.NullPointerException, since the conditional confirms
// that myStr is null when it reaches here.
System.debug(myStr.toLowerCase());
}
}
public void example3() {
Integer i; // Not initialized
Integer y = i + 2;
// throws System.NullPointerException since
// binary operation is invoked on null object
}
To fix NullPointerException issues, use one of these methods.
- Check that the object is
not-nullbefore performing the operation. - Make sure that all variables are initialized.
Avoid initializing variables to null. If your logic demands initialization to null, make sure to reassign a value to your variable before you invoke an operation on it.