Handle ValueError and ZeroDivisionError in Python with try except
Learn how to catch ValueError and ZeroDivisionError in Python with a practical safe_divide function and demonstrate error handling for invalid conversions.
Python code
21 linesdef safe_divide(numerator, denominator):
try:
result = numerator / denominator
except ValueError as e:
print(f"ValueError caught: {e}")
return None
except ZeroDivisionError:
print("Cannot divide by zero!")
return None
return result
# Test cases
print(safe_divide(10, 2)) # Expected: 5.0
print(safe_divide(10, 0)) # Expected: error message + None
print(safe_divide("10", 2)) # Expected: TypeError propagates
# Demonstrate ValueError handling
try:
number = int("abc")
except ValueError as e:
print(f"ValueError caught: {e}")
Output
5.0
Cannot divide by zero!
None
Cannot divide by zero!
None
ValueError caught: invalid literal for int() with base 10: 'abc'
How it works
The try block attempts the division, and if a ValueError or ZeroDivisionError occurs, the corresponding except block runs, printing a message and returning None. Note that safe_divide("10", 2) raises a TypeError because a string cannot be divided, and since TypeError isn't caught, it propagates. The second example demonstrates catching ValueError from int(), showing that except ValueError is commonly used for input validation.
Common mistakes
- Catching `ValueError` when the actual exception is `TypeError`, leading to unhandled errors.
- Placing `except ZeroDivisionError` before `except ValueError` when the order matters for more specific exceptions.
- Assuming `ValueError` is raised for zero division, which actually raises `ZeroDivisionError`.
- Forgetting that `int()` raises `ValueError` for non-numeric strings, not `TypeError`.
Variations
- Use `except (ValueError, ZeroDivisionError) as e:` to catch multiple exceptions in one block with a single handler.
- Use `try:` only around the conversion, separating validation from business logic.
Real-world use cases
- Validating user input in a form where a decimal string must be converted to a float, catching invalid numbers gracefully.
- Parsing configuration values from environment variables, handling cases where the value isn't a valid integer.
- Implementing a robust calculator that gives friendly errors instead of crashing on division by zero or bad inputs.
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
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
- How to Assert an Invariant After a Complex Transformation in Python easy
Keep learning
Related tutorials and quizzes for this topic.