Python Exceptions
Exception Chaining in Python
BOTIE
PEP 3134, created in 2005 for Python 3.0, addressed lost exception information and explicit exception chaining. Python’s raise ... from ... form can attach the original exception as the cause of a new one. It lets a layer explain its own operation while preserving the failure beneath it.
Sources for this history
What Should Happen to a Count That Says “Unknown”?
An import contains count fields as text. Most contain digits, while one contains the word unknown. Replacing that field with zero would create a number that the source never supplied. Stopping every future import might also be the wrong policy.
For this lesson, the importer deliberately accepts valid fields and returns the positions that need correction. We will handle that expected conversion failure narrowly. Other failures will still reach the caller instead of being swept into the same error list.
The local parser accepts small decimal whole-number text. The Python exercises use int() and actual exceptions; this workshop makes their accepted and rejected paths visible.
Step 1 of 1
Choose a Recovery Policy for Each Failure
This importer accepts valid count strings and reports invalid count strings. Other callers can choose a different policy.
| Situation | What failed | Policy in this lesson |
|---|---|---|
| The field contains "unknown" | A text-to-integer conversion | Record that position for correction |
| The parsed count is negative | The declared nonnegative-count rule | Record that position for correction |
| The caller supplies a non-text field | The parser’s representation contract | Raise TypeError to the caller |
| The processing code uses an undefined name | The implementation | Let the defect remain visible |
The field contains "unknown"
- What failed
- A text-to-integer conversion
- Policy in this lesson
- Record that position for correction
The parsed count is negative
- What failed
- The declared nonnegative-count rule
- Policy in this lesson
- Record that position for correction
The caller supplies a non-text field
- What failed
- The parser’s representation contract
- Policy in this lesson
- Raise TypeError to the caller
The processing code uses an undefined name
- What failed
- The implementation
- Policy in this lesson
- Let the defect remain visible
Read What the Exception Is Telling You
Converting text and deciding whether the number is an allowed count are separate steps. Keeping every position until the final separation lets the report identify the source field correctly.
Read Counts and Point Out the Bad Fields
The import contains ["8", "3", "5"]. Read them as [8, 3, 5] and report no rejected fields. A later import can contain unreadable text or a negative count. Keep usable counts and identify the original positions needing correction.
BOTIE
Parsed values kept beside the positions needing correction
- values
- 08
- 13
- 25
- rejected
[]
Follow the operations
1. Count fields as text
- 0"8"
- 1"3"
- 2"5"
2. Read whole numbers
- 08
- 13
- 25
3. Reject negative counts
- 08
- 13
- 25
4. Separate values from errors
- values
- 08
- 13
- 25
- rejected
[]
5. Result
- values
- 08
- 13
- 25
- rejected
[]
The local parser accepts small decimal whole-number text. The Python exercises use int() and actual exceptions; this workshop makes their accepted and rejected paths visible.
1. Read What the Exception Is Telling You
An exception interrupts the normal path through an operation. If no local handler matches it, Python passes it back through the calls that led to that operation. A traceback shows that chain and the locations involved. The final exception type and message describe the failure that reached the outer caller.
A ValueError from int("unknown") tells us that the supplied text cannot be interpreted as an integer. A TypeError can report an unsuitable argument representation. A NameError identifies a name that the program could not resolve. Read the actual message and the relevant source line rather than treating every traceback as the same kind of problem.
The caller may have enough context to recover. A small conversion function usually cannot decide whether a whole file should be rejected or a user should be asked to correct one field.
Handling belongs at a layer that can make a useful decision about the failure.
2. Keep the Try Block Narrow
The try block identifies the operations whose expected failures we intend to handle. Put the conversion there, then name ValueError in the except clause. Code after a successful conversion can live in else, so an unrelated error there is not accidentally included in the conversion handler.
The example deliberately reports a rejected position and continues. That policy is part of the importer’s contract. It would be wrong for the all-or-nothing write in the previous lesson, where one invalid item must prevent the entire write.
An except block can itself fail. It should also be ordinary, inspectable code. A complicated recovery routine is not automatically more reliable than allowing a clear failure to reach a caller.
Each field keeps its own outcome, and the invalid field is not turned into a made-up measurement.
Handle Only the Expected Conversion Failure
The importer keeps processing after the text field it knows how to reject.
fields = ['8', 'unknown', ' 3 ']
for position, text in enumerate(fields):
try:
count = int(text)
except ValueError:
print('rejected position', position)
else:
print('accepted count', count)accepted count 8
rejected position 1
accepted count 3The output reports both accepted values and the position needing correction.
Check yourself
Questions on Parts 1 and 2
Question 1 of 2
Which result matches that explicit policy?
Question data
The importer accepts valid integer strings and records the positions of invalid integer strings. The input is ["4","unknown","7"].3. Catch a Specific Category
Handlers match an exception class and its subclasses. A broad except Exception can therefore catch many failures that a program has no useful way to repair. A bare except catches even more, including exceptions normally used to interrupt or exit a program.
Catching an exception without restoring a valid state or reporting the failure hides information from the caller. Returning None or zero after an unexpected exception can make a failed operation resemble a successful one. If a sentinel result is part of an interface, document it and make sure it cannot be confused with an ordinary result.
Sometimes an outer application boundary intentionally catches Exception to return a controlled error response and record a defect. That is different from pretending a low-level operation succeeded. Do not catch BaseException casually or prevent users from interrupting work.
The right handler is determined by the recovery this layer can perform, not by how many failures one clause can silence.
4. Separate Input Rejection from a Defect
In the Pydantic lessons, ValidationError means data failed the declared validation pipeline. A wrong call inside a custom validator may instead raise TypeError. Catching only ValidationError keeps those paths distinct.
TypeError is not always a programming defect: an external caller can genuinely send the wrong representation. The important question is which representations this boundary is meant to accept, and which errors this layer promises to recover from. Our text-count importer reports invalid text contents but rejects non-text fields as a different caller error.
A test can verify that a known bad field is reported while an unexpected failure still propagates. That protects the failure policy when someone later adds a convenient-looking broad handler.
Name the specific failure your handler understands. Leave other categories available to the layer that can act on them.
5. Add Context and Preserve the Cause
A setting called timeout is more informative to an application operator than a bare conversion error. Define a small exception class derived from Exception when a caller needs a named application-level category. Raise it with an explanation of the operation that failed.
The from error clause explicitly links that new exception to the caught failure. The cause remains available through __cause__ and appears in a normal chained traceback. You can communicate the setting-level problem without losing the original conversion information.
Do not include passwords or complete private records merely to make an error more detailed. An internal diagnostic and a public response can need different amounts of information.
The message explains the setting; the cause explains the conversion.
Translate a Configuration Failure
The program catches its application-level error and inspects the preserved cause.
class SettingsError(Exception):
pass
def read_timeout(text):
try:
return int(text)
except ValueError as error:
raise SettingsError('timeout must be a whole number') from error
try:
read_timeout('later')
except SettingsError as error:
print(str(error))
print(type(error.__cause__).__name__)timeout must be a whole number
ValueErrorThe handler translated the failure without erasing where it came from.
6. Keep Cleanup Independent of Recovery
A parser can fail while a file is open. Whether we recover from that parser error is separate from whether the file must be closed. A finally block runs cleanup as control leaves the protected operation, including when an exception propagates.
Python’s with statement gives resource-owning objects a defined way to participate in that cleanup. The context-manager lesson develops the mechanism using an in-memory text buffer, so you can inspect it without creating files.
Avoid a return statement in cleanup that accidentally suppresses an exception or replaces the result being returned. Cleanup should preserve the failure unless suppressing it is an explicit and justified part of the interface.
Releasing a resource does not require pretending the operation using it succeeded.
7. Test Both the Error and Its Consequences
For the importer, test that accepted fields keep their order and that rejected positions point to the original input. A changed batch length should not break that correspondence. Include empty input and a field with surrounding spaces.
For a translated configuration failure, test the exception category, its useful message and its cause. Also test a parsed integer outside the allowed range. That second failure comes from the domain rule, not from a conversion exception, so it should not claim to have a conversion cause.
If a function changes state, inspect that state after failure. An exception assertion alone does not establish that no partial effect occurred.
A failure test checks the promised behavior of the operation, including what must remain unchanged.
Check yourself
Questions on Parts 1 to 7
Question 1 of 5
What information can this hide?
Question data
A function catches Exception and returns zero, even for an undefined variable. Zero is also a valid result.Try it with Botie
Build with Botie
Write and run Python