Guide Python Intermediate

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.

2 min read
flowchart TD V["Untrusted value\n(e.g. user input, env var)"] --> T["try:\nint(value)"] T -->|"valid"| S["Success:\nreturn converted value"] T -->|"invalid"| E["except (ValueError, TypeError):\nreturn default / log / re-prompt"]

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 like str.isdigit() can skip the exception path for simple digit strings, but try/except is 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 Exception broadly 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 skipping try/except entirely — it doesn’t handle negative numbers, decimals, or non-string inputs like None.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form