Skip to content
Python for Quantitative Finance / Files, Exceptions, and Modules

Exceptions and Control Flow

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/except block that catches a specific exception type and recovers gracefully, and predict the flow of execution when an exception is or is not raised inside the try block;
  • use except with multiple exception types, and a bare except: clause, and state when each is appropriate;
  • use raise to signal that a function cannot satisfy its specification, choosing an appropriate built-in exception type and an informative message;
  • compare an implementation using try/except against an equivalent implementation using explicit if checks, and explain why the former is often clearer and more efficient.

In this lesson

  1. Handling an exception with try/except
  2. 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 lesson

New to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.