Exercise 2.7: Handling Multiple Built-in Exceptions

Author

Chuck Nelson

Published

October 23, 2025

1 Purpose

This exercise builds on our functional TaskManager by making it more robust. A program that crashes when it receives unexpected input provides a poor user experience. Here, you will learn to anticipate and manage different kinds of common errors by using a single try block with multiple, specific catch blocks for built-in Java exceptions. This allows you to handle each error appropriately, making your application more stable and reliable.

2 What You’ll Accomplish

By the end of this exercise, you will have:

  • Used if statements to validate data and throw built-in exceptions.
  • Implemented a try block with multiple catch clauses for different exception types.
  • Handled IllegalArgumentException and IndexOutOfBoundsException gracefully.
  • Understood how to use Java’s standard exceptions to improve code quality.
  • 4. Problem-Solving and Critical Thinking:
    • 4.3 Identify, analyze, and debug software errors.
  • 5. Software Development Lifecycle:
    • 5.3 Test and debug software applications to ensure they meet requirements.
    • 5.4 Apply security and quality assurance best practices in software development.
  • Learning Objectives:
    • Throw standard Java exceptions like IllegalArgumentException.
    • Implement a try-catch block that handles multiple, distinct exception types.
    • Differentiate the handling of exceptions for invalid data versus out-of-bounds access.
  • **Knowledge, Skills, and Abilities (KSAs) from O*NET:**
    • 15-1251.00 - Computer Programmers:
      • Knowledge of computer science principles, including error handling and debugging.
      • Skill in testing and debugging software.
      • Ability to apply analytical thinking to anticipate and resolve potential issues in code.
  • Technologies:
    • Java
    • Exception Handling (try, catch)
    • IllegalArgumentException, IndexOutOfBoundsException

3 Using Java’s Built-in Exceptions

Java provides a rich library of exception classes for common errors. Using these standard exceptions is good practice because it makes your code more understandable to other developers. When another programmer sees an IllegalArgumentException, they immediately know the problem is with the data passed to the method.

In this exercise, we will focus on two very common built-in exceptions:

  • IllegalArgumentException: Thrown when a method receives an argument that is not valid. For example, a task title that is empty.
  • IndexOutOfBoundsException: Thrown when you try to access a list or array with an index that is too small (negative) or too large (greater than or equal to the size).

4 Step 1: Validate Input and Throw an Exception

Let’s modify the addTask method in TaskManager.java. It should not allow tasks with null or empty titles. If it receives one, it should throw an IllegalArgumentException.

// In TaskManager.java

public void addTask(Task task) {
  // Validate the input before processing it
  if (task == null || task.getTitle() == null || task.getTitle().trim().isEmpty()) {
    throw new IllegalArgumentException("Task and task title cannot be null or empty.");
  }
  
  // If validation passes, proceed with existing logic
  task.setId(nextTaskId);
  taskStore.add(task);
  nextTaskId++;
  System.out.println("Task added: " + task.getTitle());
}

5 Step 2: Handling Different Exceptions

Now, let’s write code in App.java that could cause different types of exceptions and handle them each with a specific message. We will use a single try block and multiple catch blocks.

// In App.java
public static void main(String[] args) {
  TaskManager manager = new TaskManager();

  try {
    // --- Scenario 1: Add a valid task (should succeed) ---
    System.out.println("Attempting to add a valid task...");
    manager.addTask(new Task("Complete Exercise 2.7", "Handle built-in exceptions."));

    // --- Scenario 2: Add an invalid task (should throw IllegalArgumentException) ---
    System.out.println("\nAttempting to add a task with an empty title...");
    manager.addTask(new Task("    ", "This should fail.")); // Invalid title

    // This next line will not be reached because the exception above will be thrown
    System.out.println("This message will not be printed.");

  } catch (IllegalArgumentException e) {
    // This block specifically catches the error from adding an invalid task
    System.err.println("Error: " + e.getMessage());
  } 

  try {
    // --- Scenario 3: Access a task with a bad index (should throw IndexOutOfBoundsException) ---
    System.out.println("\nAttempting to access a task at an invalid index...");
    // We only have one task (at index 0), so index 5 is out of bounds.
    manager.getTasks().get(5);

  } catch (IndexOutOfBoundsException e) {
    // This block specifically catches the error from accessing a bad index
    System.err.println("Error: The requested task index does not exist.");
  } catch (Exception e) {
    // A general catch-all for any other unexpected errors
    System.err.println("An unexpected error occurred: " + e.getMessage());
  }

  System.out.println("\nProgram continues to run after handling exceptions...");
}

6 Your Turn: Implement and Handle More Exceptions

Complete the steps below to delete a task from the taskStore ArrayList using an index value.

  1. Add a new deleteTaskByIndex(int index) method. Instead of finding a task by its ID, we’ll use an index.
  2. In your new deleteTaskByIndex method, use the taskStore.remove(index) method. This method will automatically throw an IndexOutOfBoundsException if the index is not valid.
  3. In App.java, add a try-catch block that calls your new deleteTaskByIndex method with an invalid index (e.g., manager.deleteTaskByIndex(10);).
  4. Make sure to catch the IndexOutOfBoundsException and print a specific, user-friendly error message.

7 Reflect and Review

CautionReflection: 3-2-1
  • 3 Things I Learned: List three new concepts or skills you learned about Java’s built-in exceptions.
  • 2 Things I Found Interesting: Mention two aspects of handling different errors in different ways.
  • 1 Question I Still Have: Write down one question you have about try-catch blocks or the throw keyword.
ImportantCheck on Learning
  • Why is the order of catch blocks important? What would happen if you put catch (Exception e) as the first block after try?
  • What is the main benefit of using IllegalArgumentException instead of a generic Exception when a method receives bad data?
  • Besides IllegalArgumentException and IndexOutOfBoundsException, name another built-in Java exception and describe a scenario where it might occur.
Back to top