Lesson 4 of 5 · 6 min · Working with data
Exceptions and reading files safely
What you will learn
- Read an error message and a traceback
- Catch specific exceptions with
tryandexcept - Use
else,finallyandraise - Open files safely with
with - Raise your own errors for bad input
In simple words
When Python cannot continue, for example dividing by zero or opening a file that is missing, it stops and raises an exception. Without a plan the whole program crashes. With try and except you say "try this, and if that particular thing goes wrong, do this instead". It is like checking if the shop is open before you walk in, and having a plan B if it is closed.
Words to know
- Exception: an error object Python raises when something goes wrong.
- Traceback: the printed trail showing which lines led to the error.
- Handle: catch an exception and respond instead of crashing.
- Context manager: the thing after
withthat sets something up and always cleans it up.
Reading a traceback
Traceback (most recent call last):
File "report.py", line 5, in <module>
print(10 / count)
ZeroDivisionError: division by zero
Read it from the bottom: the type (ZeroDivisionError) and message tell you what, the lines above tell you where. The last line of your own code in the trail is usually the one to look at.
try and except
try:
value = int("abc")
except ValueError:
print("not a number")
- Put only the risky line in
try. - Catch the specific exception you expect. A bare
except:hides every bug, including typos and Ctrl+C. - Catch several:
except (ValueError, TypeError):, or separateexceptblocks for different handling. - Get the error object:
except ValueError as error: print(error).
Common built-in exceptions: ValueError (right type, bad value), TypeError (wrong type), KeyError (missing dict key), IndexError (list index out of range), FileNotFoundError, ZeroDivisionError, AttributeError.
else and finally
try:
f = open("sales.csv")
except FileNotFoundError:
print("file missing")
else:
print("opened fine") # runs only if no exception
f.close()
finally:
print("always runs") # cleanup, exception or not
else holds code that should run only when try succeeded, which keeps the try block small. finally always runs, even after return or an unhandled exception: use it for cleanup.
Reading files with with
Never leave a file open by accident. A with block closes it for you, even if an error happens:
with open("sales.csv", encoding="utf-8") as f:
for line in f:
print(line.strip())
"r"reads (default),"w"writes and erases,"a"appends.- Always pass
encoding="utf-8"for text, otherwise the result depends on the computer's default. - Looping over
freads one line at a time, which is safe for big files;f.read()loads everything.
Combine with a handler:
try:
with open("sales.csv", encoding="utf-8") as f:
rows = f.readlines()
except FileNotFoundError:
rows = []
Raising your own
Validate input early and fail with a clear message:
def percent(part, whole):
if whole == 0:
raise ValueError("whole must not be zero")
return part / whole * 100
You can define your own exception type by subclassing Exception: class BadRowError(Exception): pass. Re-raise inside a handler with a bare raise to log and pass it on.
Look before you leap, or ask forgiveness
Two styles exist. LBYL checks first (if key in data:). EAFP tries and handles the error (try: data[key]). Python code often prefers EAFP when failure is rare and checking is awkward; for a simple dict lookup, data.get(key, default) is cleaner than either.
Common mistakes
- A bare
except:orexcept Exception: pass, which silently hides bugs. - A huge
tryblock, so you cannot tell which line failed. - Forgetting to close files; use
with. - Catching an error and carrying on with bad data. Log it, skip the row on purpose, or stop.
Try it yourself
- Write
to_int(text)that returns anint, orNonewhen the text is not a number. - Read a file that does not exist and handle the error with a friendly message.
- Write
safe_divide(a, b)that raisesValueErrorfor zero and test it withtry. - Read a CSV file line by line with
withand count the lines.
Check yourself
Why avoid a bare except:?
It catches everything, including programming errors and keyboard interrupts, and hides the real problem. Catch the specific exception you expect.
When does the else block of a try run?
Only when the try block finished without raising an exception.
What is with open(...) as f for?
It closes the file automatically when the block ends, even if an error happens inside.
Which exception does {"a": 1}["b"] raise?
KeyError.
Interview questions
What is the difference between except and finally?
except runs only when a matching exception is raised. finally always runs, for cleanup, whether or not there was an exception.
How do you raise an exception inside a function, and why?
With raise ValueError("message"). It stops the function immediately and tells the caller exactly what was wrong, instead of returning a wrong result.
What is a context manager?
An object used with with that runs setup on entry and cleanup on exit, such as opening and closing a file or acquiring and releasing a lock.
Summary
- Read tracebacks from the bottom; the last line names the error.
- Catch specific exceptions in small
tryblocks; useelseandfinally. - Open files with
withandencoding="utf-8". - Raise clear errors for bad input.
Going deeper
- Errors and exceptions: the official tutorial.
- Built-in exceptions: the full hierarchy.
- Reading and writing files:
open, modes andwith.
See how much of this you can explain
A free mock interview asks you new questions on Python essentials for analysts for Data Analyst and scores every answer, with what to fix.