Python Files & Errors
Python Exceptions
An exception is what Python creates when something goes wrong while your program runs — like dividing by zero or accessing a missing dictionary key. Understanding them is the first step to writing programs that fail gracefully instead of crashing.
What Is an Exception?
When Python hits a problem it cannot continue past, it "raises" an exception: a special object describing what went wrong. If nothing in your code handles it, the program stops immediately and Python prints a traceback showing exactly where the error happened.
numbers = [10, 20, 30]
print(numbers[5])Traceback (most recent call last):
File "app.py", line 2, in <module>
print(numbers[5])
IndexError: list index out of rangeReading a Traceback
A traceback reads bottom to top for the important parts. The last line names the exception type and message (IndexError: list index out of range). The lines above it show the exact file and line number where the failure occurred, which is your first clue for debugging.
Do not panic at a wall of red text. Scroll to the last line first — it tells you the exception type and the actual problem in plain words.
Common Built-in Exceptions
Python ships with dozens of built-in exception types, each describing a specific category of failure. Recognising the common ones by name makes debugging much faster.
| Exception | Raised When |
|---|---|
| ValueError | A value has the right type but an invalid value, e.g. int("abc") |
| TypeError | An operation is used on the wrong data type, e.g. "2" + 2 |
| IndexError | A list/tuple index is out of range |
| KeyError | A dictionary key does not exist |
| NameError | A variable is used before it is defined |
| ZeroDivisionError | Dividing a number by zero |
| FileNotFoundError | Opening a file that does not exist in read mode |
| AttributeError | Calling a method/attribute that does not exist on an object |
int("hello") # ValueError
"2" + 2 # TypeError
{"a": 1}["b"] # KeyError
10 / 0 # ZeroDivisionErrorEvery exception in Python is an object, and they all trace back to a common ancestor class called Exception. This is important later when you write try/except blocks or design your own custom exceptions, because you can catch a broad category or a very specific one.
Exceptions are not always bugs — they are a normal, expected way for a program to signal "this specific thing went wrong here."
