Why does my OpMode stop with a NullPointerException?
A NullPointerException occurs when a program attempts to call a method or access a property of an object from a variable that has a null value . This means the variable does not hold a value or the value does not exist .
In the context of an OpMode, a common cause for a NullPointerException is trying to access hardwareMap before it has been initialized . The hardwareMap variable's value is defined just before the init() method (or runOpMode() in LinearOpModes) is called . If an attempt is made to get a device from hardwareMap outside of these methods, such as when declaring a variable, hardwareMap will be null, leading to a NullPointerException .
For example, the following code will throw a NullPointerException because hardwareMap is null when clawServo is initialized:
public class CrashyOpMode extends OpMode {
Servo clawServo = hardwareMap.get(Servo.class, "claw"); // NullPointerException here
@Override
public void init() {
clawServo.setPosition(0.5);
}
}
To fix this, the device's value definition should be moved into the init() method (or runOpMode() for LinearOpModes), where hardwareMap has been properly initialized . It is also important to ensure that the device name is correctly configured in the hardware map, as get will return null if the name is not found, which would also lead to a NullPointerException when attempting to use the null object .
An example of a corrected OpMode:
public class WorkingOpMode extends OpMode {
Servo clawServo = null;
@Override
public void init() {
clawServo = hardwareMap.get(Servo.class, "claw");
clawServo.setPosition(0.5);
}
}
When an exception like a NullPointerException is thrown and not handled, the FTC SDK performs an "emergency stop" routine, halting the OpMode and displaying the full stacktrace on screen .