How to Handle ValueError Exceptions in Python
A beginner-friendly example showing how to catch ValueError and related exceptions with try-except blocks in Python.
Python code
32 linesdef divide_numbers(a, b):
try:
result = a / b
return f"{a} / {b} = {result}"
except ZeroDivisionError:
return "Error: Cannot divide by zero."
except TypeError:
return "Error: Please provide numbers, not strings."
except ValueError:
return "Error: Invalid value detected."
def parse_integer(user_input):
try:
number = int(user_input)
return f"Parsed integer: {number}"
except ValueError:
return f"Error: '{user_input}' is not a valid integer."
except TypeError:
return "Error: Input must be a string."
if __name__ == "__main__":
print("--- Division Examples ---")
print(divide_numbers(10, 2))
print(divide_numbers(10, 0))
print(divide_numbers("10", 2))
print("\n--- Integer Parsing Examples ---")
print(parse_integer("42"))
print(parse_integer("hello"))
print(parse_integer(None))
Output
--- Division Examples ---
10 / 2 = 5.0
Error: Cannot divide by zero.
Error: Please provide numbers, not strings.
--- Integer Parsing Examples ---
Parsed integer: 42
Error: 'hello' is not a valid integer.
Error: Input must be a string.
How it works
The try-except blocks catch specific exceptions raised during runtime. ZeroDivisionError triggers when dividing by zero, while TypeError catches incompatible data types. The ValueError occurs when a function receives an argument with the correct type but an invalid value, like int("hello"). Each handler returns a clear error message so the program continues instead of crashing. Multiple except clauses let you respond differently to each failure type.
Common mistakes
- Catching the base `Exception` class instead of specific exception types.
- Using `return` inside `except` blocks without considering the function flow.
- Forgetting that `ValueError` and `TypeError` are distinct — wrong type vs. invalid value.
- Not wrapping risky operations like user input parsing in try-except at all.
Variations
- Use `except (ValueError, TypeError)` to handle multiple exception types in one block.
- Add an `else` clause to run code only when no exception occurs.
Real-world use cases
- Parsing user-provided input from CLI arguments or forms into typed values.
- Validating configuration file values before using them in application logic.
- Converting external API response strings into integers for database storage.
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.