How to Handle ValueError When Converting Strings to Integers in Python

Convert text to an integer with a try-except block that catches ValueError and prints beginner-friendly error messages.

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

Python code

18 lines
Python 3.9+
def parse_number(text):
    """Convert text to an integer, showing beginner-friendly error handling."""
    try:
        number = int(text)
        print(f"Successfully parsed: {number}")
        return number
    except ValueError as e:
        print(f"Error: '{text}' is not a valid number.")
        print(f"Debugging info: {e}")
        print("Tip: Use digits only, like '42' instead of 'forty-two'.")
        return None

if __name__ == "__main__":
    # Test cases that demonstrate the ValueError handler
    parse_number("42")       # Valid input
    parse_number("hello")    # Invalid input
    parse_number("3.14")     # Float (not an integer)
    parse_number("")         # Empty string

Output

stdout
Successfully parsed: 42
Error: 'hello' is not a valid number.
Debugging info: invalid literal for int() with base 10: 'hello'
Tip: Use digits only, like '42' instead of 'forty-two'.
Error: '3.14' is not a valid number.
Debugging info: invalid literal for int() with base 10: '3.14'
Tip: Use digits only, like '42' instead of 'forty-two'.
Error: '' is not a valid number.
Debugging info: invalid literal for int() with base 10: ''
Tip: Use digits only, like '42' instead of 'forty-two'.

How it works

The int() function raises a ValueError when it receives a string that isn't a valid integer. The try block attempts the conversion, and except ValueError captures the exception object, allowing you to print its message and a friendly tip. Using return None in the except block lets callers know the conversion failed without crashing. The if __name__ == "__main__" guard ensures test cases run only when the script is executed directly. This pattern is foundational for handling user input and data parsing in Python.

Common mistakes

  • Catching a broader exception like `Exception` instead of `ValueError`, which can hide unrelated bugs.
  • Forgetting to return a value (like `None`) from the except block, causing confusing `None` returns.
  • Assuming `int()` can handle floats or numbers with commas without stripping them first.

Variations

  1. Use `text.strip()` before converting to handle surrounding whitespace.
  2. Wrap the handling in a loop to keep asking for input until a valid number is given.

Real-world use cases

  • Parsing command-line arguments that must be integers, giving clear feedback when they're invalid.
  • Reading configuration files where numeric values might be malformed, logging a helpful error.
  • Validating user input in a form before saving to a database, showing an inline error message.

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.