Skip to content

Python Exception Handling and Cleanup

Step 10 of 41

Python Exception Handling: Hierarchies, Handlers, and args

Introduction

Python exception handling depends on the class of the exception and the order of the handlers. For example, IndexError matches except LookupError because it inherits from that class. If that broad handler comes first, a later except IndexError does not run.

This lesson begins objective 2.1 of PCAP-31-03, in Exceptions (14% of the score, 5 of 40 items). You will choose handlers, trace else and finally, and inspect an exception object’s args.

Learning objectives

After this lesson you can:

  1. Write try/except blocks with one handler, several handlers, a tuple of classes and a catch-all handler.
  2. Explain the order in which except clauses are tested and why a broad class placed first hides the ones after it.
  3. Use else and finally correctly in the flow of a try statement.
  4. Navigate the built-in hierarchy (BaseException, Exception, ArithmeticError, LookupError, OSError, and others).
  5. Read the args property of an exception and bind the exception with as.
  6. Choose handlers that are specific enough to be safe.

The anatomy of try

A try statement protects a block of code. If an exception is raised inside the block, Python abandons the rest of the block and looks for a matching handler.

Python
try:
    value = int(text)
except ValueError:
    value = 0

If text is "42", no exception occurs and the except block is skipped. If text is "abc", int() raises ValueError, the remaining lines of the try block are skipped, the handler runs and execution continues after the whole statement. If the exception is not a ValueError, the handler does not match and the exception continues to travel upward.

A try statement has one or more handlers, a finally clause, or both. These clauses appear in this order when present:

Part Runs when Typical use
except Class: an exception of that class (or a subclass) was raised recovery, logging, default values
except: (bare) any exception at all, if no earlier clause matched; must be last last-resort handler
else: the try suite falls through without an exception, return, break, or continue code that depends on success
finally: when Python leaves the protected statement, including on a pending exception or return cleanup

The clauses else and finally are optional, and else is only allowed if at least one except clause exists.

Several handlers and tuples

You can list several except clauses. Python tests them from top to bottom and executes only the first one that matches.

Python
def parse(value):
    try:
        return 100 / int(value)
    except ValueError:
        print("not a number")
    except ZeroDivisionError:
        print("zero is not allowed")
    except (TypeError, KeyError):
        print("wrong type")

parse("x")      # not a number
parse("0")      # zero is not allowed
parse(None)     # wrong type  (int(None) raises TypeError)

When two exception types deserve the same reaction, give a tuple: except (TypeError, KeyError):. Always write the parentheses: before Python 3.14, except TypeError, KeyError: is a syntax error, and the exam expects the parenthesised tuple (Python 3.14 relaxes this rule only when no as name is used).

In an ordinary try/except statement, the first matching handler runs. If it finishes normally, any finally clause runs before execution continues. If the handler raises or returns, that control flow takes effect after cleanup.

The as clause and args

To inspect the exception object, bind it with as:

Python
try:
    int("abc")
except ValueError as err:
    print(err)         # invalid literal for int() with base 10: 'abc'
    print(err.args)    # ("invalid literal for int() with base 10: 'abc'",)

Built-in exceptions expose args as a tuple. For ValueError, one argument becomes its message, multiple arguments display as a tuple, and no arguments give an empty message. Some subclasses, including KeyError and OSError, customize their display or argument handling.

Python
try:
    raise ValueError("bad value", 42)
except ValueError as err:
    print(err.args)    # ('bad value', 42)
    print(err)         # ('bad value', 42)

try:
    raise ValueError
except ValueError as err:
    print(err.args)    # ()

Two small rules matter for the exam. Python clears the name bound by as when the handler ends, even if that name had an earlier binding. Using the cleared name raises NameError, or its subclass UnboundLocalError for a local variable. Save a separate reference inside the handler if you need one later. And the args of a KeyError contains the missing key, so {}["k"] produces err.args == ("k",).

The built-in hierarchy

Exceptions are objects instantiated from exception classes. The following is an abbreviated hierarchy. An except clause matches the listed class or a subclass.

Text
BaseException
 ├── SystemExit
 ├── KeyboardInterrupt
 └── Exception
      ├── ArithmeticError
      │    ├── ZeroDivisionError
      │    ├── OverflowError
      │    └── FloatingPointError
      ├── LookupError
      │    ├── IndexError
      │    └── KeyError
      ├── OSError
      │    ├── FileNotFoundError
      │    └── PermissionError
      ├── ValueError
      ├── TypeError
      ├── NameError
      ├── AttributeError
      ├── ImportError
      │    └── ModuleNotFoundError
      ├── AssertionError
      └── RuntimeError

You can verify the ancestors with __mro__, which lists a class and all its parents:

Python
print([cls.__name__ for cls in ZeroDivisionError.__mro__])
# ['ZeroDivisionError', 'ArithmeticError', 'Exception', 'BaseException', 'object']

Key consequences:

  • except ArithmeticError also catches ZeroDivisionError, OverflowError and FloatingPointError.
  • except LookupError catches both IndexError (bad list index) and KeyError (missing dictionary key). This is useful when code accesses either kind of container.
  • except OSError catches FileNotFoundError and PermissionError, because they are subclasses.
  • except Exception catches ordinary exception subclasses. It does not catch SystemExit or KeyboardInterrupt, which inherit directly from BaseException. This is intentional: pressing Ctrl+C or calling sys.exit() should normally stop the program.
  • except BaseException and a bare except: do catch these control-flow exceptions. Avoid both unless you re-raise.

Worked example: ordering of handlers

Problem. What does this program print, and is there a problem with the code?

Python
def read(items, index):
    try:
        return items[index]
    except LookupError:
        print("lookup")
    except IndexError:
        print("index")
    return None

read([1, 2, 3], 10)

Step 1: find the exception. items[10] on a three-element list raises IndexError.

Step 2: test the first handler. IndexError is a subclass of LookupError, so except LookupError matches. Python executes it and prints lookup.

Step 3: skip the rest. Only the first matching clause runs. except IndexError is never reached.

Solution. The output is lookup, and the second handler is unreachable for exceptions already caught by LookupError. The correct design puts the more specific class first (IndexError) and the more general one afterwards, or just keeps the one that is needed.

Why other answers are wrong. index would be right only if the clauses were in the opposite order. A beginner might also expect both messages to appear, but Python never runs two except clauses for one exception.

The complete flow with else and finally

The four clauses combine into a precise sequence. Study this example and trace it for three inputs.

Python
def to_int(text):
    try:
        number = int(text)
    except ValueError:
        print("invalid")
        number = -1
    else:
        print("valid")
    finally:
        print("done")
    return number
Call Printed lines Return
to_int("5") valid, done 5
to_int("x") invalid, done -1
to_int(None) done, then the traceback of an unhandled TypeError not reached

For None, int(None) raises TypeError, which is not caught by except ValueError. The finally block still runs and prints done, and then the exception continues to travel up to the caller. The return number line is not executed.

Why use else? It narrows the protected region. Code in try is guarded by the handlers; code in else is not. Put in try only the statements that can raise the exception you intend to catch.

Python
try:
    f = open("data.txt")
except FileNotFoundError:
    print("missing")
else:
    with f:
        print(f.readline())  # errors here are not caught by the earlier handler

A trap related to return: if the try block executes return, the else block is skipped (it only runs when the block ends normally), but the finally block still runs before the function actually returns.

Choosing what to catch

Handler Catches Advice
except ValueError invalid values such as int("x") precise; preferred
except (ValueError, TypeError) either of two known errors good when the reaction is identical
except LookupError IndexError and KeyError good for containers of unknown kind
except OSError file and system errors use for file operations
except Exception nearly all errors only at program boundaries, with logging
except: everything, including Ctrl+C and sys.exit() avoid

A good handler follows three rules. First, catch only what you can handle: if you do not know what to do with the error, let it travel. Second, keep the try block small, so that you know which line failed. Third, do not hide errors: an except block that contains only pass makes bugs invisible.

For tracing an imported module that fails during initialization, see module execution and entry points. To define an exception meaningful to your application, see custom Python exceptions.

Worked example: a configuration reader

Problem. A service reads a port number from a dictionary of settings. The dictionary may lack the key "port", the value may be text that is not a number, and the program must use 8080 in both cases. It must not hide any other error. Write the code and justify the handler.

Step 1: list the failures. A missing key raises KeyError. Text such as "eighty" makes int() raise ValueError. A value of None would raise TypeError, but the requirement says nothing about it, so we do not catch it.

Step 2: group the handled errors. The reaction is identical for the two handled errors, so a tuple is the natural tool.

Python
def read_port(settings):
    try:
        return int(settings["port"])
    except (KeyError, ValueError):
        return 8080

Step 3: check the behaviour.

Python
read_port({"port": "9000"})      # 9000
read_port({})                    # 8080
read_port({"port": "abc"})       # 8080
read_port({"port": None})        # TypeError propagates

Why other designs are worse. except Exception would also swallow the TypeError, hiding the bad configuration. A bare except: would additionally capture KeyboardInterrupt, so a user could not stop the program with Ctrl+C. Two separate handlers with identical bodies work but repeat code.

More examples by hierarchy

A practical program often benefits from the parent class.

Python
def average(values):
    try:
        return sum(values) / len(values)
    except ArithmeticError:
        return 0.0

print(average([]))           # 0.0  (len is 0, ZeroDivisionError is an ArithmeticError)
print(average([4, 6]))       # 5.0

With a lookup:

Python
def pick(container, key):
    try:
        return container[key]
    except LookupError as err:
        print("missing:", err.args)
        return None

pick([10, 20], 5)            # missing: ('list index out of range',)
pick({"a": 1}, "b")          # missing: ('b',)

The same handler works for a list and a dictionary because IndexError and KeyError share the ancestor LookupError. Also see how args differs: for IndexError it holds the message, for KeyError the missing key.

Quick tracing drill

Trace this function for the four calls and check your answers against the explanation.

Python
def risky(data, key):
    try:
        value = data[key]
        return 10 // value
    except KeyError:
        return "key"
    except ZeroDivisionError:
        return "zero"
    except Exception:
        return "other"

print(risky({"a": 5}, "a"))
print(risky({"a": 0}, "a"))
print(risky({"a": "x"}, "a"))
print(risky({}, "a"))
  1. data["a"] is 5 and 10 // 5 is 2, so the function returns 2 without any handler running.
  2. data["a"] is 0, so 10 // 0 raises ZeroDivisionError and the function returns "zero".
  3. 10 // "x" raises TypeError. It matches neither KeyError nor ZeroDivisionError, but it is an Exception, so the last clause returns "other".
  4. {}["a"] raises KeyError and the function returns "key".

The output is therefore 2, zero, other, key. The order of clauses is safe here because KeyError and ZeroDivisionError are unrelated to each other and the broad Exception handler is last. If you moved except Exception to the top, every call that fails would print other, and the two specific handlers would be dead code.

Common pitfalls and exam tips

  • A broad class placed first. except Exception before except ValueError makes the second clause unreachable. Many exam answers hinge on this.
  • Tuple syntax. Use parentheses around several classes, as the exam does.
  • A bare except: must be the last clause, otherwise it is a syntax error.
  • else without except is a syntax error; finally alone is allowed.
  • as names disappear after the handler.
  • Only one handler runs, even if several would match.
  • str(err) versus err.args. args is always a tuple; str(err) for KeyError("k") shows the string key with quotes.
  • Exception is not everything. SystemExit and KeyboardInterrupt pass through it.
  • Return inside try. else is skipped, finally still runs.

Exam tip. Write the class chain of the raised exception, for example IndexError -> LookupError -> Exception, and scan the except clauses from top to bottom. The first clause whose class appears in the chain wins; draw a line under it and ignore the rest.

Mini case study: the import job that never stops

A nightly job reads CSV rows and converts the third column to an integer.

Python
for row in rows:
    try:
        qty = int(row[2])
        total += qty
    except:
        pass

Operators report two problems: the totals are sometimes too low without any message, and pressing Ctrl+C does not stop the job at once.

Task. Explain both symptoms and rewrite the loop.

Solution.

  1. The bare except: catches everything, so rows with a missing column (IndexError) or text in the column (ValueError) are skipped with no trace. This explains the low totals.
  2. It also catches KeyboardInterrupt, which inherits from BaseException. The interrupt is swallowed by the handler for the current row, and the loop continues with the next row. That explains why Ctrl+C seems to do nothing.
  3. A rewrite names the expected failures, reports them, and leaves other errors alone:
Python
skipped = 0
for number, row in enumerate(rows, start=1):
    try:
        qty = int(row[2])
    except (IndexError, ValueError) as err:
        skipped += 1
        print(f"row {number} skipped: {err!r}")
    else:
        total += qty
print("skipped rows:", skipped)

The else block keeps the addition outside the protected region; Ctrl+C now interrupts the loop; and the message makes every discarded row visible.

Key terms

  • Exception: an object representing an error condition, raised during execution.
  • Handler: an except clause that processes a matching exception.
  • Hierarchy: the inheritance tree of exception classes; subclasses match parent handlers.
  • args: tuple holding the arguments passed to the exception.
  • else clause: code run when the try suite falls through normally.
  • finally clause: cleanup run when Python leaves the protected statement.
  • BaseException: the root class; its direct children include Exception, SystemExit and KeyboardInterrupt.

Summary checklist

  • I can write try/except with one class, a tuple and several clauses.
  • I know that clauses are tested top to bottom and only the first match runs.
  • A parent class in an early clause hides its subclasses later.
  • I can place else and finally and trace their order.
  • I know ArithmeticError, LookupError and OSError and their main children.
  • Exception does not include SystemExit or KeyboardInterrupt.
  • args is a tuple; the as name is deleted after the handler.
  • I avoid the bare except: and except: pass.

Official sources