How to Catch ValueError in Python (try except)
Handle invalid numeric input by catching ValueError in a try/except block and returning a friendly error message.
Python code
12 linesdef parse_number(text):
try:
number = int(text)
return f"Parsed number: {number}"
except ValueError as error:
return f"Error: '{text}' is not a valid number ({error})"
if __name__ == "__main__":
examples = ["42", "hello", "3.14", "100"]
for item in examples:
print(parse_number(item))
Output
Parsed number: 42
Error: 'hello' is not a valid number (invalid literal for int() with base 10: 'hello')
Error: '3.14' is not a valid number (invalid literal for int() with base 10: '3.14')
Parsed number: 100
How it works
The try block attempts to convert text to an integer using int(). If the input isn't a valid integer, Python raises a ValueError, which is caught by the except ValueError clause. The as error syntax binds the exception object to the variable error, allowing you to include details in your message. This pattern prevents the program from crashing and lets you handle bad input gracefully. The function returns a message either way, so the caller always gets a string.
Common mistakes
- Catching `Exception` instead of the specific `ValueError`, which hides unrelated bugs.
- Forgetting `as error`, so you can't include the exception details in your message.
- Placing the `except` block without a `try`, causing a `SyntaxError`.
Variations
- Use `except (ValueError, TypeError)` to also catch wrong types like `None`.
- Print directly instead of returning a string, especially in a script.
Real-world use cases
- Parsing user input from a CLI tool where numbers are expected but users can type anything.
- Reading configuration values from environment variables that might be malformed numbers.
- Converting query string parameters to integers in a web API before validation.
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.