LESSON · 1 OF 6

Exceptions and tracebacks

Exceptions and tracebacks

When Python hits something it can't do, dividing by zero, opening a file that isn't there, it raises an exception. An exception is Python's way of saying "I can't continue with this", and unless you handle it, the whole script stops on the spot.

What a crash looks like

Try to open a file that doesn't exist:

python
open("/etc/missing.conf")

Python prints a traceback and exits:

Traceback (most recent call last):
  File "script.py", line 1, in <module>
    open("/etc/missing.conf")
FileNotFoundError: [Errno 2] No such file or directory: '/etc/missing.conf'

Reading a traceback

A traceback is not noise, it's a map. Read it bottom to top:

  • The last line is the exception type and message. Here it's FileNotFoundError and the file it couldn't find. This tells you what went wrong.
  • The lines above show where it happened, tracing back through the calls that led there, with file names and line numbers.

The bottom line is where to look first. FileNotFoundError on a path tells you the path is wrong or the file is missing, before you read another word.

Exception types

Every failure has a type, and the type tells you the category of problem:

  • FileNotFoundError: the file or directory isn't there.
  • KeyError: a dictionary key doesn't exist.
  • ValueError: a value has the right type but a wrong content, like int("abc").
  • ZeroDivisionError: you divided by zero.

Knowing the type matters, because handling errors well means catching the specific type you expect, which the next node covers.

What this node covers

  • An exception is raised when Python can't complete an operation.
  • Unhandled, it prints a traceback and stops the script.
  • Read a traceback bottom to top; the last line is the type and message.
Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute