Validate try except ValueError handler for beginners — errors debugging

Learn how to validate user input and handle division errors safely using try/except with ValueError and ZeroDivisionError in Python.

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

Python code

51 lines
Python 3.9+
def divide_numbers(a, b):
    """Divide two numbers, catching division by zero and value errors."""
    try:
        result = a / b
    except ZeroDivisionError:
        print("Error: Cannot divide by zero!")
        return None
    except TypeError:
        print("Error: Both arguments must be numbers!")
        return None
    else:
        print(f"{a} / {b} = {result}")
        return result
    finally:
        print("Division attempt completed.")


# Edge cases to reproduce errors
print("Testing valid input:")
value = divide_numbers(10, 2)
print(f"Result returned: {value}\n")

print("Testing division by zero:")
value = divide_numbers(5, 0)
print(f"Result returned: {value}\n")

print("Testing type error:")
value = divide_numbers(8, "2")
print(f"Result returned: {value}\n")


def is_valid_age(age_str):
    """Validate user age input using try/except ValueError."""
    try:
        age = int(age_str)
        if age < 0 or age > 120:
            raise ValueError("Age must be between 0 and 120")
        return age
    except ValueError as e:
        print(f"Invalid input: {e}")
        return None


print("Validating age inputs:")
for test in ["25", "-5", "abc", "150", "70"]:
    result = is_valid_age(test)
    print(f"Input '{test}' -> {result}\n")


if __name__ == "__main__":
    print("Program finished.")

Output

stdout
Testing valid input:
Division attempt completed.
10 / 2 = 5
Result returned: 5

Testing division by zero:
Division attempt completed.
Error: Cannot divide by zero!
Result returned: None

Testing type error:
Division attempt completed.
Error: Both arguments must be numbers!
Result returned: None

Validating age inputs:
Input '25' -> 25
Input '-5' -> Invalid input: Age must be between 0 and 120
Input '-5' -> None
Input 'abc' -> Invalid input: invalid literal for int() with base 10: 'abc'
Input 'abc' -> None
Input '150' -> Invalid input: Age must be between 0 and 120
Input '150' -> None
Input '70' -> 70

Program finished.

How it works

The try block attempts the operation that might fail. The except clauses catch specific exception types: ZeroDivisionError for division by zero and TypeError for non-numeric operands. The else block runs only when no exception occurs, giving a clean place for successful-path logic. The finally block always executes, making it ideal for cleanup like closing files or logging. For age validation, int() raises ValueError on invalid strings, and you can also raise ValueError manually to enforce business rules like age ranges.

Common mistakes

  • Using a bare `except:` instead of catching specific exceptions
  • Forgetting that the `else` block only runs when no exception is raised
  • Not handling `TypeError` separately for division with non-number types
  • Raising `ValueError` but catching it in the same block without a message

Variations

  1. Use `if b == 0` to check before dividing, avoiding the exception entirely
  2. Use `try/except` with a custom exception class for age range validation instead of raising ValueError

Real-world use cases

  • Parsing numeric input from users in a CLI tool or form and returning friendly error messages
  • Reading configuration values from a file and catching invalid number formats gracefully
  • Processing sensor data where occasional invalid values must not crash the monitoring service

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.