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.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 13 views 0 copies

Python code

4 lines
Python 3.9+
try:
    number = int("not_a_number")
except ValueError:
    print("That's not a valid number. Please enter digits only.")

Output

stdout
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

  1. Use `except ValueError as e:` to access the exception message for logging.
  2. Use a loop to re-prompt the user until they enter a valid number.
  3. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.