Python Exception Hierarchy
Core idea
An exception is an object describing a failure or control event. Exception classes form a hierarchy: a subclass is a more specific kind of its parent. ValueError and TypeError derive from Exception, which derives from BaseException. An except handler for a parent class also matches its subclasses. The full handler syntax is covered next.
print(issubclass(ValueError, Exception))print(issubclass(Exception, BaseException))issubclass(child, parent) checks the inheritance relationship, not whether two classes are identical.
Catch a specific failure
try: int("tea")except ValueError: print("Invalid number")The conversion raises ValueError; the matching handler runs.
Control events are different
print(issubclass(KeyboardInterrupt, Exception))print(issubclass(KeyboardInterrupt, BaseException))KeyboardInterrupt is outside Exception so normal application handlers need not swallow an interrupt. This code only inspects classes.
Common mistake
Putting except Exception before a more specific handler hides that handler for matching subclasses. Avoid bare except and catching BaseException for routine recovery.
Practice
Predict whether except ValueError handles TypeError. Check the relationship with issubclass.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Choose a catch class
Check your understanding of exception hierarchy.
What is printed?
print(issubclass(ValueError, Exception))What is printed?
try: int("x")except ValueError: print("specific")except Exception: print("general")What is printed?
print(issubclass(KeyboardInterrupt, Exception))Which handler best targets invalid integer text?