Sub topic 1
What Exceptions Are and How to Read a Traceback
Prerequisites
This chapter assumes you can write and call Python functions, use if and loops, read a simple traceback, and define basic classes.
What Exceptions Are and How to Read a Traceback
An exception is an object Python creates when an operation cannot continue normally. Examples include ValueError for an invalid value and FileNotFoundError when a file is missing. The exception propagates up the call stack, which is the chain of functions currently calling one another. If no handler catches it, Python prints a traceback.
A traceback lists the call path from the first call to the failure. Read it from the bottom upward:
- The last line gives the exception type and message.
- The preceding frame shows where the failure occurred.
- Earlier frames show which function calls led there.
def convert(text):
return int(text)
def run():
convert("seven")
run()The final line is ValueError: invalid literal for int() with base 10: 'seven'. The traceback also identifies the line inside convert that failed.
Catching Errors with `try` and `except`
A try statement marks code that may fail. An except clause handles a matching exception. Keep the try block narrow so unrelated failures are not hidden.
try:
count = int("seven")
except ValueError as exc:
print(f"Invalid number: {exc}")The as exc part binds the exception object to a local name. You can inspect its message or other attributes.
The Exception Hierarchy
Exception classes form an inheritance hierarchy. BaseException is the root, but application code normally catches Exception or a more specific subclass. KeyboardInterrupt and SystemExit inherit directly from BaseException, so a broad except Exception does not intercept them.
Specific handlers communicate which failures you expect:
try:
value = items[index]
except IndexError:
value = NoneMultiple Handlers and Matching Order
Python tests except clauses from top to bottom and runs the first compatible one. Put subclasses before their parent classes. Otherwise, the broader handler makes the specific handler unreachable.
try:
value = int(text)
except ValueError:
print("The text is not a valid integer")
except Exception:
print("Another error occurred")Here, ValueError is checked first. Avoid bare except: because it catches system-exit signals and interrupts as well as ordinary failures.
Exercise
Why should an except ValueError clause appear before except Exception?
Show answer
Because ValueError is a subclass of Exception; the broader clause would catch it first.