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.

Easy Python 3.6+ Aug 9, 2026 Errors & debugging 12 views 0 copies

Python code

21 lines
Python 3.6+
def 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

stdout
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

  1. Use `except (ValueError, ZeroDivisionError) as e:` to catch multiple exceptions in one block with a single handler.
  2. 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

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.