Your tracker reads its expenses from receipt text. One badly typed amount in that text stops the whole report. This lesson skips the bad line instead, and lists it at the end so you can fix it.
The concept
Here is your tracker as the last lesson left it. Run it:
Receipts are not always tidy. Here someone typed the naira sign into an amount. Run this:
ValueError: invalid literal for int() with base 10: '₦1000'You met this error when you converted text with a comma in it. int reads digits, and ₦ is not a digit. It fails on the loop's second pass, and the traceback points at line 8, the int line.
The total never printed. The print comes after the loop, and Python stopped before it got there. One bad line out of three cost you the whole result.
Now run this:
Two lines: Total spent: ₦3,300, from the two good amounts, then Skipped: Airtime, Data, ₦1000. The bad line no longer stops the program. It is set aside, and the loop moves on to Suya.
Python's name for an error that happens while a program runs is an exception. The try: and except ValueError: lines handle one. Python runs the lines in the try block. When one of them fails with a ValueError, Python leaves that block and runs the except block instead. Handling an error this way is called catching it.
On the Lunch and Suya passes, nothing failed, so the except block was skipped. Either way, Python carried on after it, and the program finished.
The syntax
try:
amount = int(parts[2].strip())
amounts.append(amount)
except ValueError:
skipped.append(line)try, a colon, and an indented block. Inside it go the line that can fail, and the lines that depend on it.except, the type of error to catch, a colon, and an indented block. That block runs only when that error happens insidetry.exceptsits level withtry, the wayelsesits level withif.- When a line in the try block fails, the lines after it in that block never run.
- Either way, Python carries on from the first line after the except block.
Name the exact type of error. It is the first word on the last line of the error message: here, ValueError. An except catches only the type it names. Any other error still stops the program, so a mistake you did not expect still shows up.
The append line is inside the try block on purpose. It must run only when the amount converted. When int fails, Python leaves the block at that line, so nothing is added for the bad line. If append sat below the except block, it would run for the bad line too. amount would still hold the number from the line before, and it would be counted twice.
Keep everything else outside. In your tracker, the parts, item and category lines are not expected to fail, so they stay above the try. If one of them ever does fail, you see its error as normal.
A minimal working example
text = "₦1000"
try:
amount = int(text)
print(f"Amount: ₦{amount:,}")
except ValueError:
print("Not a number: " + text)
print("Carrying on")Output: Not a number: ₦1000, then Carrying on. Change text to "1000" and the output becomes Amount: ₦1,000, then Carrying on. The last line runs either way.
Common mistakes
You catch the wrong type. You write except TypeError: around the int line. The console shows the same error as if there were no try at all:
ValueError: invalid literal for int() with base 10: '₦1000'An except catches only the type it names. A ValueError is not a TypeError, so nothing catches it, and it stops the program. Copy the type from the last line of the error, spelled exactly. Your exercise breaks this way on purpose.
You leave out the type. An except: with no type after it is called a bare except. It catches every error, which sounds safe. Run this:
Total spent: ₦0, and all three lines skipped, even the two good ones. The try block has a typo: amonts instead of amounts. On each good line, that fails with a NameError, and the bare except catches it. Your typo now looks like two more bad receipt lines. Change except: to except ValueError: in the demo and run it again:
NameError: name 'amonts' is not defined. Did you mean: 'amounts'?This time Python's guess is right. Fix the spelling, and only the Airtime line is skipped.
You wrap the whole program in one try. Run this:
One line of output: Something went wrong. The first line was read, then the second failed. Python jumped to the except block, so Suya was never read and no total printed. The message does not say which line failed, or why. The traceback would have told you both. Put only the line that can fail, and the lines that depend on it, inside try.
Try it yourself
You will add a badly typed receipt line, watch it stop your report, then skip it.
-
Run the starting code below. Count the expenses in your report. Confirm there is one for every line in your receipt text.
-
Put your cursor in front of the closing
"""of your receipt text, and press Enter. On the new line, in front of the""", type this line. You can copy it from here:Airtime, Data, ₦1000Run it. Confirm the console shows
ValueError: invalid literal for int() with base 10: '₦1000', pointing at youramountline. None of your report printed. -
Under
expenses = [], addskipped = []. Select youramount = int(...)line and theexpenses.append(...)line under it, and press Tab to indent both. Above them, level with yourcategoryline, addtry:. Below them, level withtry:, add these two lines:except ValueError: skipped.append(line)To get there, press Enter after the
appendline, then Shift+Tab once. Run it. Confirm your full report is back, with the same expenses as in step 1. The Airtime line is not among them. -
At the very end of the file, leave a blank line, then add these lines with no indentation:
if len(skipped) > 0: print() print("Skipped lines:") for line in skipped: print(" " + line)Run it. Confirm your report now ends with
Skipped lines:, and your Airtime line under it. Theifmeans a receipt with no bad lines gets no empty section. -
Break it on purpose: change
except ValueError:toexcept TypeError:. Run it. Confirm theValueErroris back, pointing at youramountline, and your report is gone again. -
Fix it: change it back to
except ValueError:. Run it. Confirm your report returns, with theSkipped lines:section at the end.
Your tracker now survives a badly typed receipt line, and tells you which one it set aside. As your list of expenses grows, a shorter view helps. The next lesson takes part of a list, such as your last three expenses.