Try-Catch Exception Handling
What are Exceptions?
Exceptions are errors that occur during program execution that can disrupt the normal flow of your program. In robotics, exceptions might happen when sensors fail, motors disconnect, or invalid data is received. Java provides try-catch blocks to handle these errors gracefully instead of crashing your robot program.
Why Use Try-Catch?
In FRC robotics, your program must be robust and handle unexpected situations. Without proper exception handling, a single sensor failure could crash your entire autonomous routine. Try-catch blocks allow your robot to continue operating even when errors occur, providing fallback behavior and error recovery.
Basic Try-Catch Structure:
// Basic try-catch syntax
try {
// Code that might throw an exception
// This is the "risky" code
} catch (ExceptionType e) {
// Code to handle the exception
// This runs if an exception occurs
}
// Simple example with division
try {
int result = 10 / 0; // This will throw ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
System.out.println("Exception message: " + e.getMessage());
}
System.out.println("Program continues...");Common Java Exceptions
Understanding common exceptions helps you write better error handling code. Here are the most frequent exceptions you'll encounter in robot programming:
Common Exception Examples:
// 1. NumberFormatException - Invalid string to number conversion
try {
String userInput = "abc"; // Invalid number
int number = Integer.parseInt(userInput);
} catch (NumberFormatException e) {
System.out.println("Invalid number format: " + userInput);
}
// 2. ArrayIndexOutOfBoundsException - Invalid array access
try {
int[] motorPowers = {0, 1, 2, 3};
int power = motorPowers[5]; // Index 5 doesn't exist
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Motor index out of range!");
}
// 3. NullPointerException - Accessing null object
try {
String sensorName = null;
int length = sensorName.length(); // Calling method on null
} catch (NullPointerException e) {
System.out.println("Sensor object is null!");
}Multiple Catch Blocks
You can have multiple catch blocks to handle different types of exceptions differently. This allows for specific error handling based on the type of problem that occurred.
Multiple Catch Example:
import java.util.Scanner;
public class RobotSensorReader {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] sensorNames = {"Ultrasonic", "Color", "Touch", "Gyro"};
try {
System.out.print("Enter sensor index (0-3): ");
String input = scanner.nextLine();
int index = Integer.parseInt(input); // Could throw NumberFormatException
String selectedSensor = sensorNames[index]; // Could throw ArrayIndexOutOfBoundsException
System.out.println("Selected sensor: " + selectedSensor);
double reading = readSensor(selectedSensor);
System.out.println("Sensor reading: " + reading);
} catch (NumberFormatException e) {
System.out.println("[ERROR] Error: Please enter a valid number!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("[ERROR] Error: Sensor index out of range!");
System.out.println(" Valid range: 0 to " + (sensorNames.length - 1));
} catch (Exception e) {
// Generic catch for any other exceptions
System.out.println("[ERROR] Unexpected error: " + e.getMessage());
}
}
public static double readSensor(String sensorName) {
return Math.random() * 100;
}
}The Finally Block
The
finally block contains code that always executes, whether an exception occurs or not. This is perfect for cleanup operations like stopping motors, closing files, or releasing resources.Finally Block Example:
public class RobotMotorTest {
public static void main(String[] args) {
boolean motorStarted = false;
try {
System.out.println("Starting motor test...");
startMotor();
motorStarted = true;
// Simulate motor test that might fail
performMotorTest();
System.out.println("Motor test completed successfully!");
} catch (Exception e) {
System.out.println("[ERROR] Motor test failed: " + e.getMessage());
} finally {
// Always stop the motor, even if test fails
if (motorStarted) {
System.out.println("[STOP] Stopping motor for safety...");
stopMotor();
}
System.out.println("Motor test cleanup completed.");
}
}
public static void startMotor() {
System.out.println("[START] Motor started");
}
public static void stopMotor() {
System.out.println("[STOPPED] Motor stopped");
}
public static void performMotorTest() {
// Simulate a test that might fail randomly
if (Math.random() > 0.5) {
throw new RuntimeException("Motor overheated during test!");
}
System.out.println("Motor test passed");
}
}Exception Handling Best Practices:
Guidelines for Robust Robot Code:
- Be Specific: Catch specific exception types rather than generic Exception
- Log Useful Information: Include context about what the robot was doing
- Provide Fallbacks: Have backup plans when primary systems fail
- Don't Ignore Exceptions: Always handle or log exceptions appropriately
- Use Finally for Cleanup: Stop motors and release resources in finally blocks
- Fail Gracefully: Allow robot to continue operating when possible
Try It Yourself:
Exercise 1: Exception Handling Practice
- Create a safe sensor reading system with exception handling
- Build a motor control system with input validation and error recovery
- Implement a robot configuration loader with multiple exception types
- Design an autonomous routine with step-by-step error handling
Practice implementing try-catch blocks for robot programming scenarios: