Search⌘ K
AI Features

Solution: The Array Index Safeguard

Understand how to protect your Java applications from array index errors by using try-catch blocks to handle exceptions. This lesson guides you through implementing safeguards against invalid array accesses, improving program stability and error reporting.

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);
}
}
...