8.10 Safe Type Conversion
Wrapping a conversion in try/except so invalid input degrades gracefully instead of crashing, plus input validation and error handling as complementary strategies.
Wrapping a conversion in try/except lets the program degrade gracefully instead of crashing.
Using try/except
What Is It?
Wrapping a conversion call in try/except so an invalid input produces a controlled fallback instead of crashing the whole program.
def safe_int(value, default=0):
try:
return int(value)
except (ValueError, TypeError):
return default
>>> safe_int("42")
42
>>> safe_int("abc")
0
>>> safe_int(None)
0
Input Validation
Validating before converting (e.g. checking str.isdigit() first) can avoid the exception path entirely for simple cases, though try/except remains the more general and robust approach for anything beyond plain digit strings.
Error Handling
Beyond just returning a default, a production script should typically also log the invalid input it encountered, so bad data upstream gets noticed and fixed rather than silently swallowed forever.
Quick Interview Answer
“The standard pattern for safe conversion is wrapping the call in
try/except (ValueError, TypeError)and returning a sensible default or re-prompting, rather than letting the exception propagate and crash the program. Pre-validating with something likestr.isdigit()can skip the exception path for simple digit strings, buttry/exceptis the more general approach — it correctly handles every failure mode, not just the ones a hand-written validator anticipated. In production code, a caught conversion failure is usually also worth logging, so bad upstream data gets noticed rather than silently defaulted away forever.”
Common Mistakes
- Catching
Exceptionbroadly instead of the specific(ValueError, TypeError)pair, masking unrelated bugs. - Returning a default silently with no logging, letting systematically bad upstream data go unnoticed indefinitely.
- Relying only on
str.isdigit()pre-validation and skippingtry/exceptentirely — it doesn’t handle negative numbers, decimals, or non-string inputs likeNone.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form