Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Welcome to the Food Bank's Donation Import

This course shows you how to catch, throw, and tell apart JavaScript errors, and find what went wrong. Python’s try looks the same in JavaScript, but JavaScript throws less often on bad data, so code that waits for an error to reject bad data lets it slip through, and its catch takes every error, not only the ones you meant to handle. This is the last course on the beginner path.

Your project is to port a food bank’s donation import, the Python script its volunteer treasurer runs, to JavaScript. Here’s a first taste. Her script, donations.py, totals the good rows of October’s export. Here are the parts that check each amount:

Language: Python
def parse_amount(text):
    amount = float(text)
    if amount <= 0:
        raise ValueError(f"amount must be positive, got {amount}")
    return amount

def main():
    # ... reads the rows of the export ...
    total = 0
    rejected = []
    for line, row in enumerate(rows[1:], start=2):
        date, donor, amount_text = row
        try:
            amount = parse_amount(amount_text)
        except ValueError as err:
            rejected.append((line, donor, str(err)))
        else:
            total += amount
    # ... prints the report ...

Run as python donations.py october.csv, it rejects four rows, each with a reason:

Language: Program Output
6 rows, 4 rejected, total £125.00
  line 3 (D-102): could not convert string to float: 'n/a'
  line 4 (D-117): could not convert string to float: ''
  line 5 (D-104): could not convert string to float: '1,250.00'
  line 6 (D-105): amount must be positive, got -40.0

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.