How to Handle ValueError When Converting Strings to Integers in Python
Convert text to an integer with a try-except block that catches ValueError and prints beginner-friendly error messages.
Python code
18 linesdef parse_number(text):
"""Convert text to an integer, showing beginner-friendly error handling."""
try:
number = int(text)
print(f"Successfully parsed: {number}")
return number
except ValueError as e:
print(f"Error: '{text}' is not a valid number.")
print(f"Debugging info: {e}")
print("Tip: Use digits only, like '42' instead of 'forty-two'.")
return None
if __name__ == "__main__":
# Test cases that demonstrate the ValueError handler
parse_number("42") # Valid input
parse_number("hello") # Invalid input
parse_number("3.14") # Float (not an integer)
parse_number("") # Empty string
Output
Successfully parsed: 42
Error: 'hello' is not a valid number.
Debugging info: invalid literal for int() with base 10: 'hello'
Tip: Use digits only, like '42' instead of 'forty-two'.
Error: '3.14' is not a valid number.
Debugging info: invalid literal for int() with base 10: '3.14'
Tip: Use digits only, like '42' instead of 'forty-two'.
Error: '' is not a valid number.
Debugging info: invalid literal for int() with base 10: ''
Tip: Use digits only, like '42' instead of 'forty-two'.
How it works
The int() function raises a ValueError when it receives a string that isn't a valid integer. The try block attempts the conversion, and except ValueError captures the exception object, allowing you to print its message and a friendly tip. Using return None in the except block lets callers know the conversion failed without crashing. The if __name__ == "__main__" guard ensures test cases run only when the script is executed directly. This pattern is foundational for handling user input and data parsing in Python.
Common mistakes
- Catching a broader exception like `Exception` instead of `ValueError`, which can hide unrelated bugs.
- Forgetting to return a value (like `None`) from the except block, causing confusing `None` returns.
- Assuming `int()` can handle floats or numbers with commas without stripping them first.
Variations
- Use `text.strip()` before converting to handle surrounding whitespace.
- Wrap the handling in a loop to keep asking for input until a valid number is given.
Real-world use cases
- Parsing command-line arguments that must be integers, giving clear feedback when they're invalid.
- Reading configuration files where numeric values might be malformed, logging a helpful error.
- Validating user input in a form before saving to a database, showing an inline error message.
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.