How to Handle ValueError with try except in Python
Shows a beginner-friendly try/except pattern that catches ValueError when converting text to an integer, prints a helpful message, and returns None instead of crashing.
Python code
16 linesdef parse_number(text):
try:
return int(text)
except ValueError:
print(f"ValueError: '{text}' is not a valid integer.")
return None
if __name__ == "__main__":
user_input = "abc"
result = parse_number(user_input)
print(f"Parsing '{user_input}' returned: {result}")
valid_input = "42"
result = parse_number(valid_input)
print(f"Parsing '{valid_input}' returned: {result}")
Output
ValueError: 'abc' is not a valid integer.
Parsing 'abc' returned: None
Parsing '42' returned: 42
How it works
The try block attempts to convert the input string to an integer using int(). If the conversion fails because the string is not a valid number, Python raises a ValueError, which the except ValueError clause catches. Instead of terminating the program, the handler prints a clear error message and returns None to signal failure. This lets the caller continue running and decide how to handle the invalid input. The code wraps the demonstration in a if __name__ == "__main__" block so it only runs when executed directly, keeping the function reusable as a module.
Common mistakes
- Using a bare `except:` without specifying `ValueError` catches all exceptions and can hide bugs.
- Forgetting to return a value in the except block, which leads to an implicit `None` but can confuse logic.
- Calling `int()` on a non-string type like `None` or a list, which raises a `TypeError` instead of `ValueError`.
Variations
- Use `except (ValueError, TypeError):` to also catch cases where the input is not a string.
- Instead of printing, raise a custom exception or log the error for further processing.
Real-world use cases
- Parsing user input from a command-line tool where a bad number should prompt for retry, not crash the program.
- Converting strings from a config file or CSV row into types, ignoring or logging rows with invalid data.
- Handling API responses where an expected numeric field might be missing or non-numeric, allowing graceful fallback.
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.