Catch ValueError and print friendly message in Python
Wrap an int() call in a try/except block and print a friendly message when ValueError is raised.
Python code
4 linestry:
number = int("not_a_number")
except ValueError:
print("That's not a valid number. Please enter digits only.")
Output
That's not a valid number. Please enter digits only.
How it works
int("not_a_number") raises a ValueError because the string cannot be converted to an integer. The try block runs the risky code, and if a ValueError occurs, the matching except clause catches it and prints a user-friendly message instead of letting the program crash. This pattern keeps your script running and gives users clear feedback. Without the try/except, Python would terminate with an ugly traceback. This is the minimal structure you can build on for more robust input handling.
Common mistakes
- Catching a bare `except:` which also hides KeyboardInterrupt and SystemExit.
- Forgetting to specify the exception type, so you swallow unrelated errors.
- Placing the print inside the try block, which defeats the purpose of handling the error.
Variations
- Use `except ValueError as e:` to access the exception message for logging.
- Use a loop to re-prompt the user until they enter a valid number.
- Use `numbers.Number` type hints or `str.isdigit()` as a pre-check before conversion.
Real-world use cases
- Validating user input in a CLI tool that asks for a numeric ID.
- Parsing data from a file that may contain malformed numeric fields.
- Handling API responses where a numeric field might be missing or corrupt.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully 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
- How to Assert an Invariant After a Complex Transformation in Python easy
Keep learning
Related tutorials and quizzes for this topic.