Unit 3: Version Control and Troubleshooting
Runtime errors, or "Exceptions," occur while your program is executing. Your code's syntax is correct, but it encounters an unexpected situation it can't handle, causing it to crash. Learning to read these errors is the key to effective debugging.
Unlike compilation errors that prevent your code from starting, runtime errors happen when the program is already running. Think of it like a recipe: a compilation error is a typo in the instructions, while a runtime error is discovering you're out of a key ingredient midway through cooking.
When a runtime error occurs, Java prints a stack trace to the console. This is your treasure map to the bug. It tells you exactly what went wrong and where.
Exception in thread "main" java.lang.NullPointerException
at frc.robot.subsystems.ArmSubsystem.setAngle(ArmSubsystem.java:42)
at frc.robot.commands.MoveArmCommand.execute(MoveArmCommand.java:25)
at edu.wpi.first.wpilibj2.command.CommandScheduler.run(CommandScheduler.java:222)
You will encounter these common exceptions frequently. Learning to recognize them is a critical skill.
Cause: You tried to use a variable that was `null` (it pointed to nothing) as if it were a real object. This is the most common runtime error in Java.
Common Scenario: Forgetting to create a new object for a motor controller in a subsystem's constructor.
private Spark m_motor; // Declared, but never initialized. It is null!
public void spinMotor() {
m_motor.set(0.5); // CRASH! Throws NullPointerException.
}
Cause: You tried to access an element in an array using an invalid index (either negative or greater than or equal to the array's length).
Common Scenario: An "off-by-one" error in a `for` loop that iterates one time too many.
String[] names = {"Alice", "Bob"}; // Valid indices are 0 and 1
System.out.println(names[2]); // CRASH! Index 2 is out of bounds.
Cause: An exceptional arithmetic condition occurred, most commonly division by zero.
Common Scenario: Dividing a number by a variable that happens to be zero.
int x = 10; int y = 0; int result = x / y; // CRASH! Cannot divide by zero.
Question: You see a `NullPointerException` in the stack trace. The first line of your code mentioned is `Intake.java:35`. What is the most likely cause of the problem?