Branching on a Failed Conversion

A failed conversion provides an observable result that can guide how a program reports invalid data.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Keep the scoped operation small
  2. Separate validity from representation
  3. Translate only the failure the caller can fix
  4. Check the effect of conversion before later work starts

Keep the scoped operation small

Python's int("9") succeeds and int("nine") raises ValueError. A handler near the conversion can report which field needs a numeric entry. Reading the traceback structure can help identify when another operation in a broad protected block raised the same type.

Separate validity from representation

With minimum value one, "0" parses successfully and then fails the domain check. Test all three cases to keep the reported cause accurate. The distinction between parsing and validation gives the caller a stable set of outcomes.[1][2]

Translate only the failure the caller can fix

Suppose a reader expects an integer count and receives "none". The conversion can raise a known exception and the surrounding routine can report “enter a whole number” for the count. If a large protected block also formats a receipt and the formatter raises the same general exception type, reporting the count as invalid misidentifies the failed step. Make the protected operation sufficiently narrow to identify its responsibility. See catching an exception near its source.

Check the effect of conversion before later work starts

Given "0", conversion yields zero. A policy requiring one through ten rejects it at a later check. Given "7", both checks succeed. Include these three cases as independent tests and verify no reservation or record creation occurs when an input is invalid.

If the input may be optional, decide whether an absent field gets a default before conversion. An empty but present field can have another policy. Parsing and domain validation and optional record fields help construct an error interface callers can use without decoding a traceback.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩