Choose a Subject and Handle Errors

A program becomes more useful when the person running it can tell it what to work on, for example which file to open. It also becomes easier to trust when, if something goes wrong, it says what happened in plain words instead of stopping with a wall of text.

Words typed after the program name

When you run a program from the terminal, you can type more words after its file name, separated by spaces. These extra words are called command-line arguments. They let the same program do different work on each run without changing its code: one run can open one file, the next run another.

Python hands these words to the program through the sys module from the standard library. After import sys, the name sys.argv refers to a list. Its first item, at index 0, is the name of the program file itself. The words you typed after it follow, from index 1 on.

A file args.py with just two lines, import sys and print(sys.argv), shows this list when you run it:

A program that prints the list it received
$ uv run args.py notes.txt 3
['args.py', 'notes.txt', '3']
sys.argv for that command
  1. 'args.py' the program
  2. 'notes.txt' first word typed
  3. '3' second word typed

Two details in this output matter. First, the word you typed first is sys.argv[1], not sys.argv[0]. Second, every item is a string, even '3': the terminal only passes text, so a program that needs a number converts it with int() itself.

With uv run, every word after the file name goes to your program and none of them to uv. If you want to give uv an option of its own, it goes before the file name.

True or false?

After running uv run args.py notes.txt, the value of sys.argv[0] is the string notes.txt.

False. Index 0 holds the program name, args.py. The first word typed after it is at index 1.

If you type uv run args.py 3, then sys.argv[1] is the string 3, not the number 3.

True. Every item of sys.argv is a string. Use int(sys.argv[1]) to get a whole number.

Exceptions: errors that happen while the program runs

A syntax error stops Python before the program starts, because Python cannot read the file. Many mistakes only show up later, while the program is running: the file to open is not there, a list has fewer items than the code expects, a word cannot be turned into a number. When one of these happens, Python creates an exception: an object that describes what went wrong. Then Python raises it. Raising means that the line that was running stops there, and the problem is passed upward, to whatever part of the program may be ready to deal with it.

Every exception has a type, and the name of the type says what kind of problem it is. Here are a few you meet early:

Exception typeRaised whenA line that raises it
FileNotFoundErrora file to open does not existPath('nots.txt').read_text()
IndexErrora list position is past the end['a', 'b'][2]
KeyErrora dictionary has no such key{'a': 1}['b']
ValueErrora value has the right type but cannot be usedint('three')

If nothing in the program handles the exception, the program stops at once. The lines after the failing one never run, and Python prints an error report called a traceback. Stopping is not the only possible outcome, though: a program can catch an exception it expects and carry on, as a later section shows.

True or false?

When an exception is raised and nothing handles it, the lines after the failing line still run before the program ends.

False. The program stops at the failing line. Nothing after it runs.

The name FileNotFoundError tells you what went wrong before you read anything else in the report.

True. The type of an exception names the kind of problem: here, a file that was asked for and does not exist.

Reading a traceback from the bottom

Take a program show.py that reads the file named by its first argument. It starts with import sys and from pathlib import Path. On line 4 it does name = sys.argv[1]. If you run it without typing a file name, sys.argv holds only the program name, so index 1 is past the end of the list. Python raises an exception and prints this traceback:

Running show.py with no argument
$ uv run show.py
Traceback (most recent call last):
  File "/home/ana/quiz/show.py", line 4, in <module>
    name = sys.argv[1]
           ~~~~~~~~^^^
IndexError: list index out of range

Read it from the bottom up, in three steps:

  1. The last line says what happened. Before the colon is the type, IndexError. After it is the message, list index out of range, which adds the detail.
  2. The lines just above say where. File "...show.py", line 4 names the file and the line number, and in <module> means the top level of the file, outside any function.
  3. The line of code is shown under it, and the marks below it point at the part of the line that failed: here, the [1].

The first line, Traceback (most recent call last):, tells you the order of what follows. Each File ... line, with the code shown under it, is one entry. When the failing line is inside a function, the traceback lists one entry for each call on the way there, starting with the oldest. The most recent one, the line that actually failed, sits last, right above the type and message:

A failure inside a function
Traceback (most recent call last):
  File "/home/ana/quiz/words.py", line 4, in <module>
    print(first_word([]))
          ~~~~~~~~~~^^^^
  File "/home/ana/quiz/words.py", line 2, in first_word
    return words[0]
           ~~~~~^^^
IndexError: list index out of range

The line where Python noticed the problem is not always the line to change. If a file name is misspelled when the program is started, the traceback points at the line that opens the file, but the fix is to type the name correctly. The traceback tells you where to start looking, and the type and message tell you what to look for. Some tracebacks also list entries inside the files of a library you called; your own file's entries tell you which of your lines started the call.

True or false?

In a traceback, the entry right above the last line is the place where the error happened.

True. Entries go from the oldest call to the most recent, so the line that raised the exception is the last entry, just above the type and message.

The first entry under Traceback (most recent call last) is the line that failed.

False. The first entry is the oldest call. The line that failed is the last entry, at the bottom.

Handling an expected error with try and except

Some errors are not mistakes in the code at all. A user can type the name of a file that does not exist, and no amount of careful programming prevents that. For such an expected error, the program can catch the exception and explain the problem in its own words. That is what try and except do.

show.py, explaining a missing file
import sys
from pathlib import Path

name = sys.argv[1]
try:
    text = Path(name).read_text(encoding="utf-8")
    print(text)
except FileNotFoundError:
    print(f"There is no file called {name}. Check the spelling.")

The indented block under try: runs first. What happens next depends on whether an exception is raised in it:

  • Run the try block
  • No exception except block is skipped
  • FileNotFoundError rest of try skipped, except block runs
  • Any other type program stops with a traceback
  • Continue after the try statement
  • Run the try block to No exception
  • Run the try block to FileNotFoundError
  • Run the try block to Any other type
  • No exception to Continue after the try statement
  • FileNotFoundError to Continue after the try statement

Now a misspelled name gives a calm sentence instead of a traceback:

$ uv run show.py nots.txt
There is no file called nots.txt. Check the spelling.

Only an exception of the type named after except is caught. If the block raised an IndexError, this except clause would not match, and the program would stop with a traceback as before. A try can have several except clauses, one per expected type, each with its own message; Python uses the first one that matches.

Keep the try block short: put in it only the lines that can raise the error you expect. Then a message such as "there is no file called..." can only ever mean what it says.

True or false?

When the file exists, the line inside the except block also runs, after print(text).

False. The except block runs only when the named exception is raised in the try block. Otherwise it is skipped.

A try block with except FileNotFoundError does not catch an IndexError raised inside it.

True. A clause catches only its own type (and the more specific types that belong to it). Any other type stops the program as usual.

Why not catch every error at once

Python lets you write except Exception:, or even a bare except: with no type, and both catch nearly any error. It can look like a safe way to make sure the program never stops. The trouble is that it also catches the errors you did not expect, which are usually real bugs, and gives them the wrong explanation.

A typo, hidden by a catch-all
try:
    text = Path(nmae).read_text(encoding="utf-8")
    print(text)
except Exception:
    print(f"There is no file called {name}. Check the spelling.")

The variable is misspelled, so Python raises a NameError: no name nmae exists. That is a bug in the code, and a traceback would point straight at line 2. But the catch-all catches it too, and no traceback appears. Run the program with notes.txt, and it prints "There is no file called notes.txt" even when the file is right there. The person running the program checks the spelling of a file name that was never the problem, and the real cause stays hidden.

A bare except: goes further: it also catches KeyboardInterrupt, the exception Python raises when you press Ctrl+C to stop a program, so a stuck program may refuse to stop. The Python documentation advises naming the specific types you mean to handle and letting every other exception through, so it shows up as a traceback you can read and fix.

True or false?

Writing except Exception: makes a program safer, because it can no longer stop with a traceback.

False. It hides real bugs behind a message meant for a different problem. A traceback for an unexpected error is what lets you find and fix it.

Naming one exception type in except lets an unexpected error still stop the program and show its traceback.

True. Only the named type is handled. Everything else passes through, so a bug is reported with its type, message and line.