Try Except ValueError in Python: Handle Conversion Errors

Catch ValueError exceptions when converting strings to integers or performing arithmetic, returning None on failure instead of crashing.

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

Python code

33 lines
Python 3.9+
def convert_to_int(value):
    try:
        return int(value)
    except ValueError as error:
        print(f"Conversion failed: {error}")
        print(f"Problem value was: {repr(value)}")
        return None


def divide_numbers(numerator, denominator):
    try:
        result = numerator / denominator
        return result
    except ValueError as error:
        print(f"ValueError: {error}")
        return None


if __name__ == "__main__":
    # Example 1: Success
    print("=== Example 1 ===")
    converted = convert_to_int("42")
    print(f"Converted: {converted}\n")

    # Example 2: ValueError
    print("=== Example 2 ===")
    converted = convert_to_int("hello")
    print(f"Converted: {converted}\n")

    # Example 3: ValueError dividing
    print("=== Example 3 ===")
    result = divide_numbers(10, "five")
    print(f"Division result: {result}")

Output

stdout
=== Example 1 ===
Converted: 42

=== Example 2 ===
Conversion failed: invalid literal for int() with base 10: 'hello'
Problem value was: 'hello'
Converted: None

=== Example 3 ===
ValueError: unsupported operand type(s) for /: 'int' and 'str'
Division result: None

How it works

try blocks let you run code that might raise an exception, and except ValueError catches only that specific error type. The as error clause binds the exception object, giving you access to its message via str(error). Using repr() in the second print reveals the exact value that caused the problem, including quotes for strings. Returning None on failure makes callers check the result instead of crashing, a common pattern for defensive parsing. This keeps your program running even when user input is invalid.

Common mistakes

  • Catching all exceptions with bare `except:` instead of narrowing to `ValueError`
  • Forgetting to check the return value for `None` before using the result
  • Using `print(str(value))` instead of `repr()` misses invisible characters like spaces
  • Putting too much code inside the `try` block, masking where the error occurred

Variations

  1. Use `except (ValueError, TypeError):` to catch both conversion and type errors together
  2. Raise a custom exception instead of returning None: `raise ValueError(f"Bad value: {value}")`

Real-world use cases

  • Parsing user-entered numbers from web forms without crashing the app on bad input.
  • Converting API response fields that may contain strings instead of numbers.
  • Handling malformed configuration values with graceful fallbacks in CLI tools.

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.