Skip to main content

Programming fundamentals · Beginner · 18 min

Handle errors with try and except in Python

By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)

You will break a small file-averaging script three ways on purpose, then catch each error by name, raise your own clear errors, and end with a script that reports exactly what went wrong and exits with the right status.

On this page

Programs meet problems they cannot fix on their own: a file that is not there, a number typed with a comma, a list with nothing in it. In Python each of these problems is an exception. If nothing handles it, the program stops and prints a traceback, a report that ends with the exception's name and a short message.

In this tutorial you write a short script that prints the average of the numbers in a text file. You then make it fail three ways on purpose: a missing file, a bad number on line 3 and an empty file. For each one you learn a different tool: try and except to catch a named exception, raise to report a problem in your own words, a custom exception class, and else and finally for code that runs only on success or always. You finish with a script that checks several files, says exactly what is wrong with each one, still exits cleanly, and a rule of thumb for when to catch an error and when to let the program crash.

The examples use python3. On Windows outside WSL, type py instead. On an Android phone, the Termux app can install Python with pkg install python; everything here then runs offline, with no mobile data used after the install.

Step 1 · Write a script that averages a file

Make a folder for this tutorial, create a file with four numbers, one per line, and write the first version of the script:

Bash
mkdir -p ~/errors-demo
cd ~/errors-demo
printf '12.5\n8\n15.25\n4\n' > good.txt
cat > average.py <<'PY'
import sys

path = sys.argv[1]

with open(path, encoding="utf-8") as f:
    numbers = [float(line) for line in f]

print(f"average of {len(numbers)} numbers: {sum(numbers) / len(numbers):.2f}")
PY
python3 average.py good.txt

printf writes the four lines into good.txt; each \n is a line break. The cat > average.py <<'PY' line writes everything up to the closing PY into average.py. You can type the same lines into a text editor instead.

Line by line, the script does this:

  • import sys loads the module that gives you the command-line arguments.
  • path = sys.argv[1] takes the first word after the script name, here good.txt.
  • with open(path, encoding="utf-8") as f: opens the file for reading and closes it again when the block ends.
  • [float(line) for line in f] turns each line into a decimal number. float ignores the line break and spaces around the number.
  • The last line divides the sum by the count. :.2f shows two decimal places.

Check it worked

The output is average of 4 numbers: 9.94. The four numbers add up to 39.75, and 39.75 divided by 4 is 9.9375, which rounds to 9.94.

Step 2 · Break it three ways

Make two more files. In bad.txt, line 3 uses a comma as the decimal mark, as people write it in many countries. empty.txt has nothing in it. Then run the script on those two and on a file that does not exist:

Bash
printf '12.5\n8\n15,25\n4\n' > bad.txt
: > empty.txt
python3 average.py missing.txt || echo "exit status $?"
python3 average.py bad.txt || echo "exit status $?"
python3 average.py empty.txt || echo "exit status $?"

: > empty.txt creates an empty file. || echo "exit status $?" prints the exit status when the command fails. A program that ends normally exits with status 0; anything else means it failed.

Each run prints a traceback. Read the last line of each one. It names the exception and gives a message:

  • missing.txt ends with FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'.
  • bad.txt ends with ValueError: could not convert string to float: '15,25\n'.
  • empty.txt ends with a line that starts ZeroDivisionError:. The list of numbers is empty, so the script divides 0 by 0.

The lines above the last one show where in the script it happened. The tutorial on reading a Python traceback covers those lines in detail.

Check it worked

You see three tracebacks, each followed by exit status 1. Write down the three exception names, FileNotFoundError, ValueError and ZeroDivisionError: you catch each one by that name in the next steps.

Step 3 · Catch a missing file by name

A missing file is a problem the user can fix, so the script should tell them plainly instead of showing a traceback. Wrap the part that can fail in try, and say what to do in except:

Bash
cat > average.py <<'PY'
import sys

path = sys.argv[1]

try:
    with open(path, encoding="utf-8") as f:
        numbers = [float(line) for line in f]
except FileNotFoundError as err:
    print(f"error: no file called {err.filename!r}", file=sys.stderr)
    sys.exit(1)

print(f"average of {len(numbers)} numbers: {sum(numbers) / len(numbers):.2f}")
PY
python3 average.py missing.txt || echo "exit status $?"
python3 average.py bad.txt || echo "exit status $?"

What the new lines do:

  • try: starts a block that Python watches. If an exception happens inside it, Python stops running the block and looks for a matching except.
  • except FileNotFoundError as err: matches only that one exception. as err gives the exception object a name, so you can read details from it. err.filename is the path that could not be opened, and !r prints it in quotes.
  • file=sys.stderr sends the message to standard error, the stream meant for problems, so it stays separate from the program's normal output.
  • sys.exit(1) ends the program with status 1, so other programs and scripts can see it failed.

Check it worked

The first run prints error: no file called 'missing.txt' and exit status 1, with no traceback. The second run still prints the ValueError traceback: an except handles only the exceptions it names, and everything else carries on as before.

Why not catch everything

You can write except: with no name, and it catches every exception. That hides your own mistakes. Try this script, which has a typo, numbrs instead of numbers:

Bash
cat > bare.py <<'PY'
try:
    with open("good.txt", encoding="utf-8") as f:
        numbers = [float(line) for line in f]
    print(sum(numbrs) / len(numbers))
except:
    print("could not read the file")
PY
python3 bare.py

It prints could not read the file, although the file is fine. The real problem was a NameError from the typo, and the bare except turned it into a wrong message. A bare except also catches Ctrl+C (KeyboardInterrupt), so the user cannot stop the program. except Exception: is only a little better. Name the exceptions you expect and know how to handle.

Step 4 · Report the bad line with your own ValueError

The message could not convert string to float: '15,25\n' does not say which file or which line. A file with 2,000 lines needs better. Move the reading into a function, convert one line at a time, and when a line fails, raise a new ValueError that says exactly where:

Bash
cat > average.py <<'PY'
import sys


def read_numbers(path):
    numbers = []
    with open(path, encoding="utf-8") as f:
        for line_number, line in enumerate(f, start=1):
            text = line.strip()
            try:
                numbers.append(float(text))
            except ValueError:
                raise ValueError(f"{path} line {line_number}: {text!r} is not a number") from None
    return numbers


path = sys.argv[1]

try:
    numbers = read_numbers(path)
except FileNotFoundError as err:
    print(f"error: no file called {err.filename!r}", file=sys.stderr)
    sys.exit(1)
except ValueError as err:
    print(f"error: {err}", file=sys.stderr)
    sys.exit(1)

print(f"average of {len(numbers)} numbers: {sum(numbers) / len(numbers):.2f}")
PY
python3 average.py bad.txt || echo "exit status $?"

What is new:

  • enumerate(f, start=1) gives each line with its number, counting from 1 like a text editor does.
  • line.strip() removes the line break and spaces, so the message shows '15,25' and not '15,25\n'.
  • raise ValueError(...) creates an exception and throws it, exactly as Python did for you before. Here the message is yours.
  • from None tells Python not to print the original exception as well. Your message already says everything, so the old one would only add noise. Leave it out and Python shows both, with the line During handling of the above exception, another exception occurred.
  • Below the function, a second except clause catches the ValueError and prints its message. One try can have several except clauses; Python uses the first one that matches.

Check it worked

The output is error: bad.txt line 3: '15,25' is not a number, then exit status 1. Open bad.txt in your editor and check that line 3 really is the one with the comma.

If your users write decimals with a comma, you could accept both with float(text.replace(",", ".")). Decide that on purpose; do not let a crash decide it for you.

Step 5 · Catch the division by zero

The empty file still crashes. Catch ZeroDivisionError the same way. The division moves inside the try, so its result is saved in result:

Bash
cat > average.py <<'PY'
import sys


def read_numbers(path):
    numbers = []
    with open(path, encoding="utf-8") as f:
        for line_number, line in enumerate(f, start=1):
            text = line.strip()
            try:
                numbers.append(float(text))
            except ValueError:
                raise ValueError(f"{path} line {line_number}: {text!r} is not a number") from None
    return numbers


path = sys.argv[1]

try:
    numbers = read_numbers(path)
    result = sum(numbers) / len(numbers)
except FileNotFoundError as err:
    print(f"error: no file called {err.filename!r}", file=sys.stderr)
    sys.exit(1)
except ValueError as err:
    print(f"error: {err}", file=sys.stderr)
    sys.exit(1)
except ZeroDivisionError:
    print(f"error: {path} has no numbers", file=sys.stderr)
    sys.exit(1)

print(f"average of {len(numbers)} numbers: {result:.2f}")
PY
python3 average.py empty.txt || echo "exit status $?"
python3 average.py good.txt

Check it worked

The empty file prints error: empty.txt has no numbers and exit status 1. good.txt still prints average of 4 numbers: 9.94.

This works, but it relies on a side effect. ZeroDivisionError says how the code failed, not why. If you later add another division to the try block and it has a bug, this except would report "has no numbers" for a file that has plenty. The next step names the real problem instead.

Step 6 · Define your own exception

You can create an exception type for a problem that belongs to your program. It is a class that inherits from Exception, and it can be this short:

Bash
cat > average.py <<'PY'
import sys


class EmptyFileError(Exception):
    """Raised when a file has no numbers to average."""


def read_numbers(path):
    numbers = []
    with open(path, encoding="utf-8") as f:
        for line_number, line in enumerate(f, start=1):
            text = line.strip()
            try:
                numbers.append(float(text))
            except ValueError:
                raise ValueError(f"{path} line {line_number}: {text!r} is not a number") from None
    return numbers


def average(numbers, path):
    if not numbers:
        raise EmptyFileError(f"{path} has no numbers to average")
    return sum(numbers) / len(numbers)


path = sys.argv[1]

try:
    numbers = read_numbers(path)
    result = average(numbers, path)
except FileNotFoundError as err:
    print(f"error: no file called {err.filename!r}", file=sys.stderr)
    sys.exit(1)
except (ValueError, EmptyFileError) as err:
    print(f"error: {err}", file=sys.stderr)
    sys.exit(1)

print(f"average of {len(numbers)} numbers: {result:.2f}")
PY
python3 average.py empty.txt || echo "exit status $?"

How it fits together:

  • class EmptyFileError(Exception): makes a new exception type. The text in triple quotes is a docstring, a short description of the class. The class needs no other code: it gets everything, including the message, from Exception.
  • average checks for the problem before it divides. if not numbers: is true when the list is empty, and raise EmptyFileError(...) stops the function with your own error.
  • except (ValueError, EmptyFileError) as err: catches either type with one clause. Write the types in brackets, separated by a comma.

A ZeroDivisionError can now only mean a real bug, and it would show up as a traceback, which is what you want for a bug.

Check it worked

The output is error: empty.txt has no numbers to average and exit status 1. Run python3 average.py bad.txt and python3 average.py missing.txt again: their messages are unchanged.

Step 7 · See when else and finally run

A try statement can have two more parts. else runs only when the try block raised nothing. finally runs every time, whether the block succeeded, an except handled an error, or an error was not caught at all. Run this small script to see the order:

Bash
cat > flow.py <<'PY'
def check(text):
    print(f"--- checking {text!r}")
    try:
        value = float(text)
    except ValueError:
        print("except: not a number")
    else:
        print(f"else: got {value}")
    finally:
        print("finally: done")


check("4.5")
check("four")
check(None)
PY
python3 flow.py || echo "exit status $?"

float(None) raises a TypeError, which no except here names.

Check it worked

The output is:

Text
--- checking '4.5'
else: got 4.5
finally: done
--- checking 'four'
except: not a number
finally: done
--- checking None
finally: done

After the last finally: done comes a traceback ending in TypeError, then exit status 1. The finally block ran even though the program was about to crash. That makes it the place for clean-up and summaries that must always happen.

Step 8 · Check several files and exit cleanly

Now put it all together. The final script takes any number of files, reports each one, and keeps going after a problem. else prints the average only for files that worked, finally prints a summary every time, and the exit status is 1 if any file had a problem:

Bash
cat > average.py <<'PY'
"""Print the average of the numbers in one or more text files."""

import sys


class EmptyFileError(Exception):
    """Raised when a file has no numbers to average."""


def read_numbers(path):
    numbers = []
    with open(path, encoding="utf-8") as f:
        for line_number, line in enumerate(f, start=1):
            text = line.strip()
            try:
                numbers.append(float(text))
            except ValueError:
                raise ValueError(f"{path} line {line_number}: {text!r} is not a number") from None
    return numbers


def average(numbers, path):
    if not numbers:
        raise EmptyFileError(f"{path} has no numbers to average")
    return sum(numbers) / len(numbers)


def main(paths):
    if not paths:
        print("usage: python3 average.py FILE [FILE ...]", file=sys.stderr)
        return 2
    checked = 0
    problems = 0
    try:
        for path in paths:
            try:
                numbers = read_numbers(path)
                result = average(numbers, path)
            except FileNotFoundError:
                print(f"error: {path}: file not found", file=sys.stderr)
                problems += 1
            except (ValueError, EmptyFileError) as err:
                print(f"error: {err}", file=sys.stderr)
                problems += 1
            else:
                print(f"{path}: average {result:.2f} of {len(numbers)} numbers")
            checked += 1
    finally:
        print(f"checked {checked} of {len(paths)} files, {problems} with problems")
    return 1 if problems else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
PY
python3 average.py good.txt bad.txt empty.txt missing.txt || echo "exit status $?"
python3 average.py good.txt
echo "exit status $?"

What changed from the last version:

  • main returns a number instead of calling sys.exit in several places. The last line, sys.exit(main(sys.argv[1:])), turns that number into the exit status: 0 for success, 1 if a file had a problem, 2 for a usage mistake.
  • if __name__ == "__main__": runs main only when you start the file as a script, not when another file imports it.
  • The inner try sits inside the loop, so one bad file is reported and the loop moves on to the next.
  • The outer try and finally wrap the whole loop, so the summary prints even if an unexpected error stops the loop.

Check it worked

The first run prints good.txt: average 9.94 of 4 numbers, three error: lines (one each for bad.txt, empty.txt and missing.txt), then checked 4 of 4 files, 3 with problems and exit status 1. The order of the lines can vary a little, because errors go to a different stream. The second run prints the average, checked 1 of 1 files, 0 with problems and exit status 0.

Step 9 · Decide when to catch and when to crash

Give the script something it was not written for, a folder instead of a file:

Bash
mkdir -p not-a-file
python3 average.py good.txt not-a-file || echo "exit status $?"

Check it worked

You see the average for good.txt, checked 1 of 2 files, 0 with problems, a traceback ending in IsADirectoryError, and exit status 1. The summary comes before the traceback because finally runs before Python prints the uncaught error. On Windows the error is usually PermissionError instead. The script did not catch this error because you did not plan for it, and that is the right result: the traceback shows exactly what happened and where, and finally still printed the summary.

Use this rule of thumb for your own code:

  • Catch an exception when you know what it means and can do something useful: explain it to the user, skip one item and carry on, try again, or use a sensible default. A missing file or a typing mistake fits.
  • Let it crash when it means a bug, or when there is nothing sensible to do. A NameError, a TypeError from passing the wrong thing, or an error you never expected belongs in a traceback, where you can see it and fix the cause.
  • Catch the narrowest exception you can, in the smallest try block you can. Never write except: pass, which hides every problem and leaves nothing to debug.

When you have finished, delete the demo folder:

Bash
cd ~
rm -rf ~/errors-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.