How to Handle ValueError with try except in Python

Shows a beginner-friendly try/except pattern that catches ValueError when converting text to an integer, prints a helpful message, and returns None instead of crashing.

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

Python code

16 lines
Python 3.9+
def parse_number(text):
    try:
        return int(text)
    except ValueError:
        print(f"ValueError: '{text}' is not a valid integer.")
        return None


if __name__ == "__main__":
    user_input = "abc"
    result = parse_number(user_input)
    print(f"Parsing '{user_input}' returned: {result}")

    valid_input = "42"
    result = parse_number(valid_input)
    print(f"Parsing '{valid_input}' returned: {result}")

Output

stdout
ValueError: 'abc' is not a valid integer.
Parsing 'abc' returned: None
Parsing '42' returned: 42

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 a valid number, Python raises a ValueError, which the except ValueError clause catches. Instead of terminating the program, the handler prints a clear error message and returns None to signal failure. This lets the caller continue running and decide how to handle the invalid input. The code wraps the demonstration in a if __name__ == "__main__" block so it only runs when executed directly, keeping the function reusable as a module.

Common mistakes

  • Using a bare `except:` without specifying `ValueError` catches all exceptions and can hide bugs.
  • Forgetting to return a value in the except block, which leads to an implicit `None` but can confuse logic.
  • Calling `int()` on a non-string type like `None` or a list, which raises a `TypeError` instead of `ValueError`.

Variations

  1. Use `except (ValueError, TypeError):` to also catch cases where the input is not a string.
  2. Instead of printing, raise a custom exception or log the error for further processing.

Real-world use cases

  • Parsing user input from a command-line tool where a bad number should prompt for retry, not crash the program.
  • Converting strings from a config file or CSV row into types, ignoring or logging rows with invalid data.
  • Handling API responses where an expected numeric field might be missing or non-numeric, allowing graceful fallback.

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.