Every program in this unit has, so far, simply crashed whenever something unanticipated happened — dividing by zero, converting
'abc' to an int, opening a file that does not exist. This is Python raising an exception and, absent any handling code, terminating the program. This note shows how to handle an exception with try/except, turning what would be a crash into a controlled, anticipated branch of the program's logic — and argues, following Guttag directly, that exceptions are best understood not merely as error signals but as a genuine control-flow mechanism, often producing cleaner code than the equivalent explicit-checking alternative.Learning objectives. By the end of this note you should be able to:
- write a
try/exceptblock that catches a specific exception type and recovers gracefully, and predict the flow of execution when an exception is or is not raised inside thetryblock; - use
exceptwith multiple exception types, and a bareexcept:clause, and state when each is appropriate; - use
raiseto signal that a function cannot satisfy its specification, choosing an appropriate built-in exception type and an informative message; - compare an implementation using
try/exceptagainst an equivalent implementation using explicitifchecks, and explain why the former is often clearer and more efficient.
In this lesson
- Handling an exception with
try/except - Exceptions as a control-flow mechanism, not just an error signal
Before you start
The full lesson, with worked examples and exercise solutions, is for members.
Read the full lessonNew to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.