Lesson 9: Error Handling — Exceptions Done Right
Programs fail. Files go missing, networks drop, users type letters where numbers belong, and a single unhandled error can crash a whole program. Python's answer is the exception: when something goes wrong, Python raises an exception object, and execution jumps out of the normal flow to the nearest matching handler. If nothing handles it, the program stops and prints a traceback. Learning to handle exceptions well is what separates a script that works on a good day from a tool you can trust.
The basic shape is try / except / else / finally. Code that might fail goes in the try block. If an exception of the named type is raised, the matching except block runs. The else block runs only if nothing went wrong — a good place for code that should not itself be protected. The finally block always runs, success or failure, which makes it the right place for cleanup such as closing a file. The example below reads a number from a file and shows all four parts working together.
def read_number(path):
try:
with open(path) as f:
text = f.read().strip()
except FileNotFoundError:
print(f"no file named {path}")
return None
except OSError as exc:
print(f"could not read {path}: {exc}")
return None
else:
try:
return int(text)
except ValueError:
print(f"{path} does not contain a number")
return None
finally:
print("read attempt finished")
print(read_number("missing.txt"))
Catch what you can handle — and only that
The most common exception mistake is catching too much. A bare except: swallows every error, including the ones you never expected, and hides bugs that you desperately need to see. Always name the exception type you expect — ValueError, FileNotFoundError, KeyError — and keep the try block as small as possible, so that only the risky lines are protected. If a line inside the try raises a different error, you want it to crash loudly during testing rather than be silently eaten.
The second habit is raising exceptions of your own, with clear messages. When your code detects a bad state — a negative deposit, a missing configuration value — raise ValueError("...") is far kinder than returning a magic value like -1 and hoping the caller notices. And when you catch an exception only to raise a different one, use raise ... from exc so the original cause stays visible in the traceback. Python's own style guide calls this EAFP — easier to ask for forgiveness than permission — try the operation, and handle the failure, rather than checking every precondition first.
Going further
Exceptions form a hierarchy, and knowing the common types helps you catch precisely. ValueError means a value of the right type but the wrong content, such as int("hello"). TypeError means the wrong type altogether, such as adding a number to a string. KeyError means a missing dictionary key, IndexError a list index out of range, and FileNotFoundError a missing file. Catching the specific type, rather than a broad Exception, is what keeps a handler from accidentally swallowing a bug it was never meant to handle.
There is one more pattern worth learning: exception chaining. When you catch an exception and raise a different one in response, writing raise ValueError("bad data") from exc keeps the original exception attached as the cause, so the traceback shows both — the low-level failure and the high-level meaning you gave it. Without the from, Python still shows the original as context, but the explicit form says clearly that the new exception was raised because of the old one. It is a small courtesy to whoever debugs your code later, and that person is often you.
A habit worth building is to write the exception handling at the same time as the code that needs it, not afterwards. When you write a function that opens a file, ask immediately what happens if the file is missing; when you convert user input to a number, ask what happens if the input is not a number. The answer is usually a short try block with a named exception and a helpful message. Programs written this way fail gracefully from the start, instead of crashing the first time a real user does something unexpected — and real users, as you will discover, are wonderfully creative at doing unexpected things.
Key Terms
- Exception
- An object Python raises when something goes wrong, interrupting the normal flow of the program.
- try / except
- The block that attempts risky code and handles a named exception if one is raised.
- else (in try)
- A block that runs only if the try block finished without an exception.
- finally
- A block that always runs, whether or not an exception occurred; used for cleanup.
- Traceback
- The report Python prints for an unhandled exception, showing the chain of calls that led to it.
- raise
- The statement that creates and throws an exception, optionally with a message.
- EAFP
- Easier to ask for forgiveness than permission: try the operation and handle failure, rather than checking first.
Discussion Questions
- Why is a bare except: dangerous? Give an example of a bug it could hide.
- When should a function raise an exception, and when should it return None or a default value instead?
- What is the difference between the else and finally parts of a try statement? When would you use each?
Practice Questions
- What runs if the file exists but contains the text "hello"?
- Does the
finallyblock run when the file is missing? - Why should the
tryblock be kept small? - Write code that raises a
ValueErrorwith the message "age cannot be negative" when age is below zero. - What does
raise ValueError("bad") from excdo differently from a plain raise?
Show answers
- The ValueError handler prints that the file does not contain a number, and the function returns None. int("hello") raises ValueError, caught by the inner except.
- Yes — finally always runs. It prints "read attempt finished" even though the FileNotFoundError handler already returned.
- So that only the risky lines are protected. A wide try can swallow unexpected errors from unrelated code and hide real bugs.
if age < 0: raise ValueError("age cannot be negative")Raising with a clear message tells the caller exactly what went wrong.- It keeps the original exception as the cause in the traceback. Anyone reading the traceback can see both the original error and the new one.