Search⌘ K
AI Features

Solution: The Array Index Safeguard

Explore how to protect Java programs from runtime errors by wrapping risky array accesses in try blocks and catching ArrayIndexOutOfBoundsException. Understand how this exception safeguard provides meaningful error messages and keeps applications running smoothly.

We'll cover the following...
Java 25
public class DailyPlanner {
public static void getTask(int taskNumber) {
String[] schedule = {
"Check Emails",
"Team Standup",
"Client Call",
"Project Review",
"Submit Report"
};
try {
// Convert 1-based input to 0-based index and access array
System.out.println("Task: " + schedule[taskNumber - 1]);
} catch (ArrayIndexOutOfBoundsException e) {
// Handle cases like taskNumber=0 (index -1) or taskNumber=10 (index 9)
System.out.println("Error: Task number must be 1-5.");
}
}
public static void main(String[] args) {
// Test case 1: Valid input (User wants 2nd task)
System.out.println("--- Requesting Task #2 ---");
getTask(2);
// Test case 2: Invalid input (User wants 10th task)
System.out.println("\n--- Requesting Task #10 ---");
getTask(10);
}
}
...