How to Use try except ValueError in Python to Parse Numbers
Convert strings to integers safely with try/except ValueError and TypeError, returning a value-or-error tuple.
Python code
20 linesdef parse_number(text):
"""Safely convert a string to an integer, handling errors gracefully."""
try:
value = int(text)
return value, None
except ValueError as error:
return None, f"Conversion failed: {error}"
except TypeError as error:
return None, f"Wrong type provided: {error}"
if __name__ == "__main__":
test_inputs = ["42", "hello", "7.5", None]
for item in test_inputs:
result, error = parse_number(item)
if error:
print(f"Input '{item}' -> ERROR: {error}")
else:
print(f"Input '{item}' -> SUCCESS: {result}")
Output
Input '42' -> SUCCESS: 42
Input 'hello' -> ERROR: Conversion failed: invalid literal for int() with base 10: 'hello'
Input '7.5' -> ERROR: Conversion failed: invalid literal for int() with base 10: '7.5'
Input 'None' -> ERROR: Wrong type provided: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
How it works
The try block attempts int(text) and signals success by returning (value, None). On a ValueError (e.g., non-numeric string) or TypeError (e.g., None), the handler returns (None, error_message) instead of crashing. The tuple pattern lets callers check the second element to know if conversion failed, avoiding exceptions at the call site. Because int() raises ValueError for most bad strings and TypeError for wrong types, catching both covers common failure modes. This design keeps the function pure and easy to test, with no side effects or printed output inside.
Common mistakes
- Catching `Exception` too broadly and hiding real bugs
- Forgetting `TypeError` when `None` or a float-like object is passed
- Returning `None` for both error and value, confusing the caller
- Swallowing the error without saving the message for debugging
Variations
- Use `try` with a single `except (ValueError, TypeError)` to simplify if you don't need to distinguish error types.
- Use `if isinstance(text, str):` checks before converting to avoid exceptions entirely.
Real-world use cases
- Parsing user input from a CLI or web form where invalid numbers must show a friendly error.
- Validating configuration file values before using them in a data pipeline.
- Handling messy CSV or API text fields that may contain non-numeric strings.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.