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:
- Write
try/exceptblocks with one handler, several handlers, a tuple of classes and a catch-all handler. - Explain the order in which
exceptclauses are tested and why a broad class placed first hides the ones after it. - Use
elseandfinallycorrectly in the flow of atrystatement. - Navigate the built-in hierarchy (
BaseException,Exception,ArithmeticError,LookupError,OSError, and others). - Read the
argsproperty of an exception and bind the exception withas. - 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.
try:
value = int(text)
except ValueError:
value = 0If 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.
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:
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.
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.
BaseException
├── SystemExit
├── KeyboardInterrupt
└── Exception
├── ArithmeticError
│ ├── ZeroDivisionError
│ ├── OverflowError
│ └── FloatingPointError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── OSError
│ ├── FileNotFoundError
│ └── PermissionError
├── ValueError
├── TypeError
├── NameError
├── AttributeError
├── ImportError
│ └── ModuleNotFoundError
├── AssertionError
└── RuntimeErrorYou can verify the ancestors with __mro__, which lists a class and all its parents:
print([cls.__name__ for cls in ZeroDivisionError.__mro__])
# ['ZeroDivisionError', 'ArithmeticError', 'Exception', 'BaseException', 'object']Key consequences:
except ArithmeticErroralso catchesZeroDivisionError,OverflowErrorandFloatingPointError.except LookupErrorcatches bothIndexError(bad list index) andKeyError(missing dictionary key). This is useful when code accesses either kind of container.except OSErrorcatchesFileNotFoundErrorandPermissionError, because they are subclasses.except Exceptioncatches ordinary exception subclasses. It does not catchSystemExitorKeyboardInterrupt, which inherit directly fromBaseException. This is intentional: pressing Ctrl+C or callingsys.exit()should normally stop the program.except BaseExceptionand a bareexcept: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?
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.
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.
try:
f = open("data.txt")
except FileNotFoundError:
print("missing")
else:
with f:
print(f.readline()) # errors here are not caught by the earlier handlerA 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.
def read_port(settings):
try:
return int(settings["port"])
except (KeyError, ValueError):
return 8080Step 3: check the behaviour.
read_port({"port": "9000"}) # 9000
read_port({}) # 8080
read_port({"port": "abc"}) # 8080
read_port({"port": None}) # TypeError propagatesWhy 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.
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.0With a lookup:
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.
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"))data["a"]is 5 and10 // 5is 2, so the function returns 2 without any handler running.data["a"]is 0, so10 // 0raisesZeroDivisionErrorand the function returns"zero".10 // "x"raisesTypeError. It matches neitherKeyErrornorZeroDivisionError, but it is anException, so the last clause returns"other".{}["a"]raisesKeyErrorand 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 Exceptionbeforeexcept ValueErrormakes 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. elsewithoutexceptis a syntax error;finallyalone is allowed.asnames disappear after the handler.- Only one handler runs, even if several would match.
str(err)versuserr.args.argsis always a tuple;str(err)forKeyError("k")shows the string key with quotes.Exceptionis not everything.SystemExitandKeyboardInterruptpass through it.- Return inside
try.elseis skipped,finallystill runs.
Exam tip. Write the class chain of the raised exception, for example
IndexError -> LookupError -> Exception, and scan theexceptclauses 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.
for row in rows:
try:
qty = int(row[2])
total += qty
except:
passOperators 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.
- 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. - It also catches
KeyboardInterrupt, which inherits fromBaseException. 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. - A rewrite names the expected failures, reports them, and leaves other errors alone:
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
exceptclause 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.elseclause: code run when thetrysuite falls through normally.finallyclause: cleanup run when Python leaves the protected statement.BaseException: the root class; its direct children includeException,SystemExitandKeyboardInterrupt.
Summary checklist
- I can write
try/exceptwith 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
elseandfinallyand trace their order. - I know
ArithmeticError,LookupErrorandOSErrorand their main children. -
Exceptiondoes not includeSystemExitorKeyboardInterrupt. -
argsis a tuple; theasname is deleted after the handler. - I avoid the bare
except:andexcept: pass.
Official sources
- Python Institute, PCAP-31-03 syllabus: https://pythoninstitute.org/pcap-31-03-exam-syllabus (opens in a new tab)
- Python tutorial, Errors and Exceptions: https://docs.python.org/3.14/tutorial/errors.html (opens in a new tab)
- Built-in exceptions and hierarchy: https://docs.python.org/3.14/library/exceptions.html (opens in a new tab)
