SypherTec
…
PART 3 · 05 OF 086 MIN READUPDATED 20 NOV 2026

try and except: Skipping a Bad Line Instead of Crashing

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:

WHERE YOU LEFT OFF · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

Receipts are not always tidy. Here someone typed the naira sign into an amount. Run this:

ONE BAD AMOUNT · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output
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:

SKIPPING THE BAD LINE · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

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 inside try.
  • except sits level with try, the way else sits level with if.
  • 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

main.py
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:

AN EXCEPT WITH NO TYPE · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

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 TRY AROUND EVERYTHING · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

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.

  1. Run the starting code below. Count the expenses in your report. Confirm there is one for every line in your receipt text.

  2. 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, ₦1000

    Run it. Confirm the console shows ValueError: invalid literal for int() with base 10: '₦1000', pointing at your amount line. None of your report printed.

  3. Under expenses = [], add skipped = []. Select your amount = int(...) line and the expenses.append(...) line under it, and press Tab to indent both. Above them, level with your category line, add try:. Below them, level with try:, add these two lines:

    except ValueError:
        skipped.append(line)

    To get there, press Enter after the append line, 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.

  4. 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. The if means a receipt with no bad lines gets no empty section.

  5. Break it on purpose: change except ValueError: to except TypeError:. Run it. Confirm the ValueError is back, pointing at your amount line, and your report is gone again.

  6. Fix it: change it back to except ValueError:. Run it. Confirm your report returns, with the Skipped lines: section at the end.

TRY IT YOURSELF · PYTHON
Tab indents. Press Escape, then Tab, to leave the editor.
CONSOLE
no output

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.

QUIZ · 3 QUESTIONSCheck what stuckStart the quiz
PART 3 · 05 OF 08❮❯