How to Handle ValueError with try-except in Python
Build a beginner-friendly division calculator that catches ValueError and ZeroDivisionError with try-except blocks.
Python code
25 linesdef 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
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
- Use `float()` inside a helper that returns `None` on invalid input and loop outside.
- 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
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.