8.9 Type Conversion Errors
The three exception types behind nearly every conversion failure — ValueError, TypeError, and OverflowError — and the common causes that trigger each.
Three exception types account for nearly every conversion failure — recognizing them immediately tells you what went wrong.
ValueError
Raised when the type is correct but the actual value can’t be parsed into the target type — e.g. a string that isn’t a valid number.
>>> int("abc")
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: 'abc'
TypeError
Raised when the conversion doesn’t even make sense for that type at all — e.g. trying to convert None or a list directly into an int.
>>> int(None)
Traceback (most recent call last):
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
OverflowError
Raised when a numeric result is too large to be represented — rare with Python’s arbitrary-precision ints, but real for float, which has finite range.
>>> float(2) ** 10000
Traceback (most recent call last):
OverflowError: (34, 'Numerical result out of range')
Common Causes
- Converting user input without validating it first (see 8.10 Safe Type Conversion)
- Assuming an API/CSV/JSON field is always the type expected
- Trying to parse a decimal string directly with
int()instead of going throughfloat()first
Quick Interview Answer
“Three exceptions cover almost every conversion failure:
ValueError, when the type is right but the value can’t be parsed — likeint('abc');TypeError, when the conversion doesn’t make sense for that type at all — likeint(None); andOverflowError, when a numeric result is too large to represent, which is rare for Python’s arbitrary-precisionintbut real forfloat’s finite range. The most common real-world trigger is converting untrusted input — user input, an API field, a CSV cell — without validating it first.”
Common Mistakes
- Catching a bare
except:instead of the specific exception type, hiding bugs unrelated to the conversion itself. - Not distinguishing
ValueErrorfromTypeErrorwhen handling a conversion — both can happen from the same call site depending on the input, and often both need catching together (see 8.10 Safe Type Conversion).
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form