...

/

Error Handling and Refinement

Error Handling and Refinement

Add edge cases and exception handling to our Budget Tracker App.

We began this project by gathering requirements from a simulated client. Our AI Copilot helped us quickly generate a functional core, and it worked flawlessly in our tests. The code accepted the income and logged expenses, just as we wanted. However, in the real-world, users aren’t always perfect. What happens when they make a mistake?

Let’s find out.

The widget below contains the code we just generated. Run it as instructed. When you see the prompt that says Enter your monthly income, type the words five hundred, instead of entering the number 500.

import java.util.*;

public class BudgetTracker {
    static double income = 0.0;
    static List<Map<String, Object>> expenses = new ArrayList<>(); 
    // Each expense is a map: {"category": String, "amount": Double}

    static List<String> allowedCategories = Arrays.asList(
        "Food", "Rent", "Transport", "Entertainment",
        "Utilities", "Health", "Education", "Other"
    );

    public static void addIncome(String amount) {
        income = Double.parseDouble(amount); // risky if input is not numeric
    }

    public static void addExpense(String category, String amount) {
        Map<String, Object> expense = new HashMap<>();
        expense.put("category", category);
        expense.put("amount", Double.parseDouble(amount));
        expenses.add(expense);
    }

    public static void runCLI() {
        Scanner sc = new Scanner(System.in);
        System.out.println("Welcome to Budget Tracker!");
        System.out.print("Enter your monthly income: ");
        String incomeInput = sc.nextLine();
        addIncome(incomeInput); // crash if non-numeric entered!
    }

    public static void main(String[] args) {
        runCLI();
    }
}
Test your project with the wrong user input

The app crashed, and the terminal is filled with this red text: Exception in thread "main" java.lang.NumberFormatException: For input string: "five hundred".

What went wrong?

The AI-generated code expected a numeric value. It attempted to convert my text "five hundred" into a number using Double.parseDouble(). As the text was not numeric, the program raised a NumberFormatException and stopped running.

The AI’s goal was to generate a solution based on the most common and ideal scenario. It is assumed that a user would always input a valid number because that’s what a Budget Tracker implies. This type of code is great for a rapid ...