Syntax Errors and Runtime Failures
Locate a failure by asking whether the language can parse the source and whether evaluation reaches a valid operation.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Parsing comes first
A missing closing parenthesis can prevent a whole Python file from running. The diagnostic points to where parsing became impossible or where the parser expected more input. Start by inspecting the line above the reported location and checking pairs of delimiters. This follows the same distinction that guides reading a traceback.
When valid code fails
The statement cost = 12 / count is syntactically valid. If execution reaches it with count equal to zero, Python raises ZeroDivisionError. The same line works with count = 3. It may be skipped entirely under a condition. Record the value of count and the branch that ran in an execution trace before changing the arithmetic.[1]
Isolate two different failure stages
A malformed layout can stop Python from preparing source for execution. In the example below, an unmatched parenthesis would make the whole file unparseable even if the call appeared in an unreachable branch. With the opening and closing syntax balanced, Python can proceed. Only the arguments and selected operations determine whether a division later fails.
def minutes_per_record(minutes, records):
if records == 0:
return None
return minutes / records
assert minutes_per_record(15, 3) == 5
assert minutes_per_record(15, 0) is None
Here zero records have a documented absent result. The guard must be reached before evaluating the division. A caller wanting zero as a measured duration has another valid case: with three records and zero minutes, the returned value is zero. The difference between zero and absence belongs in the function contract.
Keep three diagnostic cases apart
First check whether the source was accepted. If a diagnostic points to a closing bracket, inspect the nested structures that came before it. Second, when execution starts and an exception appears, follow the traceback to the operation and capture its actual arguments. Third, check ordinary wrong results as well. The function above could accidentally reverse the two operands without any syntax or execution exception on positive inputs. Tests that predict the result before running it reveal that class of defect.
For practice, predict how a record count supplied as the text "0" behaves if no parser runs before this function. The equality guard will treat it differently from the integer zero, and division with that text still fails. This locates a missing type-conversion step rather than a missing arithmetic guard.