How to catch ValueError in Python and print a friendly message

This code defines a function that safely converts text to an integer, catches ValueError, and prints a friendly message instead of crashing.

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

Python code

13 lines
Python 3.9+
def parse_number(text):
    try:
        return int(text)
    except ValueError:
        print("Oops! That's not a valid number.")
        return None

if __name__ == "__main__":
    result = parse_number("abc")
    if result is None:
        print("Parsing failed.")
    else:
        print(f"Parsed value: {result}")

Output

stdout
Oops! That's not a valid number.
Parsing failed.

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 numeric, Python raises a ValueError. The except ValueError clause catches that specific exception, prints a friendly message, and returns None. The if __name__ == "__main__": guard ensures the demo code runs only when the script is executed directly, not when imported. The function returns None on failure, allowing the caller to handle the error gracefully.

Common mistakes

  • Catching a bare `except:` which hides unexpected errors like TypeError.
  • Forgetting to return a value in the except block, leading to implicit None but sometimes confusing control flow.
  • Assuming int() raises ValueError for all invalid inputs, but it also raises ValueError for empty strings or whitespace.

Variations

  1. Use `try/except` with a custom exception message and re-raise if needed.
  2. Use `int(text, base=10)` to control allowed bases.

Real-world use cases

  • Validating user input in CLI tools before performing numeric calculations.
  • Parsing configuration values from environment variables where a non-numeric value should not crash the service.
  • Handling malformed numeric fields in data ingestion pipelines and logging a warning instead of failing the batch.

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.