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.
Python code
33 linesdef 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
=== 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
- Use `except (ValueError, TypeError):` to catch both conversion and type errors together
- 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
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.