How to Handle ValueError with try-except in Python

Build a beginner-friendly division calculator that catches ValueError and ZeroDivisionError with try-except blocks.

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

Python code

25 lines
Python 3.9+
def get_number(prompt="Enter a number: "):
    while True:
        try:
            value = float(input(prompt))
            return value
        except ValueError:
            print("That's not a valid number. Please try again.")


def divide_numbers(a, b):
    try:
        result = a / b
        return result
    except ZeroDivisionError:
        print("Error: Cannot divide by zero!")
        return None


if __name__ == "__main__":
    print("Welcome to the division calculator!")
    num1 = get_number("Enter the first number: ")
    num2 = get_number("Enter the second number: ")
    result = divide_numbers(num1, num2)
    if result is not None:
        print(f"{num1} / {num2} = {result}")

Output

stdout
Welcome to the division calculator!
Enter the first number: abc
That's not a valid number. Please try again.
Enter the first number: 10
Enter the second number: 0
Error: Cannot divide by zero!

Welcome to the division calculator!
Enter the first number: 10
Enter the second number: 2
10.0 / 2.0 = 5.0

How it works

The try block contains code that may raise exceptions. If a ValueError occurs (e.g., when float() receives non-numeric input), the except ValueError block runs and prints a message, then the loop continues prompting. Similarly, ZeroDivisionError is caught when dividing by zero, returning None instead of crashing. Using while True ensures the user retries until valid input is provided. Returning None on failure allows the caller to check the result safely.

Common mistakes

  • Catching too broad an exception (e.g., bare `except:`) instead of specific types.
  • Forgetting to re-prompt in a loop after catching ValueError.
  • Not handling ZeroDivisionError separately when doing arithmetic.

Variations

  1. Use `float()` inside a helper that returns `None` on invalid input and loop outside.
  2. Add a check for `if b == 0` before dividing to avoid relying on exceptions.

Real-world use cases

  • Building CLI tools that validate user input for numeric configuration values.
  • Parsing data from external sources where values may be malformed or missing.
  • Implementing safe arithmetic in financial calculations to avoid crashes on zero divisors.

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.