Throwing Your Own Errors
The welcome video’s JavaScript report rejected two rows with the reason ValueError is not
defined. In this lesson, you found out why, by porting the line in Joan’s Python script that
refuses a refund, like line 6 of the October export, -40.00.
For text like n/a, float() raises a ValueError on its own. A refund is a number, though,
so parse_amount() raises its own ValueError, with a message that says what arrived. Joan
calls it on line 6’s amount and logs the error’s type and its message:
def parse_amount(text):
amount = float(text)
if amount <= 0:
raise ValueError(
f"amount must be positive, got {amount}"
)
return amount
try:
parse_amount("-40.00")
except ValueError as err:
print(type(err).__name__, "-", err)
Python prints ValueError - amount must be positive, got -40.0.