Menu
Coddy logo textTech

Handling Errors

Part of the Fundamentals section of Coddy's Swift journey — lesson 83 of 86.

challenge icon

Challenge

Easy

In the previous lesson, you implemented the "Clear all expenses" feature. Now, add error handling for invalid inputs throughout the expense tracker.

Modify your code to handle invalid inputs gracefully:

  1. When the user enters an invalid menu option (anything other than "1", "2", "3", "4", or "5"), print Invalid option. Please try again.
  2. When adding an expense (option "1"), if the input cannot be converted to a valid Double, print Invalid amount. Expense not added. and return to the menu without adding anything to the array
  3. All other functionality should continue working as before

Expected behavior:

  • Invalid menu choices display an error message and show the menu again
  • Invalid expense amounts display an error message and return to the menu
  • Valid inputs continue to work as implemented in previous lessons

Example interaction:

1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
7
Invalid option. Please try again.
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
abc
Invalid amount. Expense not added.
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
25.0
Expense added!
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
2
Your expenses:
- $25.0
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
5
Goodbye!

Try it yourself

// Daily Expense Tracker - Menu Display

var expenses: [Double] = []

while true {
    // TODO: Write your code below to print the menu options
    // Each option should be on its own line with the format: "number. option text"
    print("1. Add expense")
    print("2. View all expenses")
    print("3. Show total and average")
    print("4. Clear all expenses")
    print("5. Exit")
    
    let choice = readLine()
    
    if choice == "1" {
        print("Enter expense amount:")
        if let input = readLine(), let amount = Double(input) {
            expenses.append(amount)
            print("Expense added!")
        }
    } else if choice == "2" {
        if expenses.isEmpty {
            print("No expenses recorded.")
        } else {
            print("Your expenses:")
            for expense in expenses {
                print("- $\(expense)")
            }
        }
    } else if choice == "3" {
        if expenses.isEmpty {
            print("No expenses to calculate.")
        } else {
            let total = expenses.reduce(0, +)
            let average = total / Double(expenses.count)
            print("Total: $\(total)")
            print("Average: $\(average)")
        }
    } else if choice == "4" {
        expenses.removeAll()
        print("All expenses cleared!")
    } else if choice == "5" {
        print("Goodbye!")
        break
    } else {
        print("Coming soon...")
    }
}

All lessons in Fundamentals