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.

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

Python code

12 lines
Python 3.9+
def 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

stdout
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

  1. Use `except (ValueError, TypeError)` to also catch wrong types like `None`.
  2. 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

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.