Exceptions
Understand errors and how Java reports them.
An exception is an error that occurs while your program is running. When an exception happens, Java stops the current operation and prints information about what went wrong.
Learning to read exceptions is an important debugging skill.
Stack Trace
When an exception occurs, Java prints a stack trace.
Exception in thread "main" java.lang.NullPointerException
at org.firstinspires.ftc.teamcode.Robot.drive(Robot.java:42)The stack trace tells you:
- What type of exception occurred
- Which file it happened in
- Which line caused the problem
Always start by looking at the first line in your own code.
Common Exceptions
NullPointerException
This happens when you try to use an object that hasn't been created.
DcMotor motor = null;
motor.setPower(1.0); // ErrorThis is one of the most common exceptions in FTC.
ArrayIndexOutOfBoundsException
This happens when you access an index that doesn't exist.
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // ErrorRemember that arrays start at index 0.
IllegalArgumentException
Some methods only accept certain values.
servo.setPosition(2.0); // ErrorAlways check the documentation to see what values are allowed.
try-catch
Sometimes you can handle exceptions using a try-catch block.
try {
// Code that might fail
} catch (Exception e) {
e.printStackTrace();
// Fallback
}Most FTC code doesn't use try-catch very often. It's usually better to fix the root cause of the exception.
Tips for Debugging
- Read the exception message.
- Find the line where the exception occurred.
- Check the values of your variables.
- Use telemetry to print information while debugging.
Key Takeaways
- Exceptions are runtime errors.
- The stack trace tells you where the error occurred.
NullPointerExceptionis one of the most common FTC errors.- Fix the cause instead of hiding exceptions.
Was this resource helpful?
