How to Handle ValueError and Multiple Exceptions in Python
This code demonstrates try/except blocks for beginners, handling ZeroDivisionError, TypeError, and ValueError with two practical functions: dividing numbers and parsing strings to floats.
Python code
41 linesdef divide_numbers(a, b):
"""Divide two numbers with error handling for beginners."""
try:
result = a / b
print(f"{a} / {b} = {result}")
return result
except ZeroDivisionError:
print(f"Error: Cannot divide {a} by zero!")
except TypeError:
print(f"Error: Both arguments must be numbers. Got {a} and {b}.")
except ValueError:
print(f"Error: Invalid value provided: {a}, {b}")
except Exception as e:
print(f"Unexpected error: {type(e).__name__} - {e}")
return None
def parse_number(text):
"""Convert text to a number with ValueError handling."""
try:
number = float(text)
print(f"Parsed '{text}' successfully -> {number}")
return number
except ValueError:
print(f"ValueError: '{text}' is not a valid number.")
return None
except TypeError:
print(f"TypeError: Expected a string, got {type(text).__name__}.")
return None
if __name__ == "__main__":
# Test the division function
divide_numbers(10, 2) # Works fine
divide_numbers(10, 0) # ZeroDivisionError
divide_numbers(10, "five") # TypeError
# Test the parsing function
parse_number("3.14") # Valid number
parse_number("hello") # ValueError
parse_number(None) # TypeError
Output
10 / 2 = 5.0
5.0
Error: Cannot divide 10 by zero!
Error: Both arguments must be numbers. Got 10 and five.
Parsed '3.14' successfully -> 3.14
3.14
ValueError: 'hello' is not a valid number.
TypeError: Expected a string, got NoneType.
How it works
The try block runs code that might fail. If an exception occurs, Python checks each except clause in order and runs the first matching one. Order matters: ZeroDivisionError is a subclass of ArithmeticError, not Exception, but both are caught here. The ValueError in parse_number catches cases where float() can't convert the input, like non-numeric strings. Finally, the catch-all Exception ensures unexpected errors are reported instead of crashing the program.
Common mistakes
- Catching exceptions too broadly first, like `except Exception`, which hides specific error types.
- Forgetting that `ZeroDivisionError` only triggers for numeric zero, not strings like '0'.
- Assuming `float()` handles None or other types gracefully — it raises TypeError instead of ValueError.
- Not returning a fallback value from except blocks, leading to implicit `None` returns.
Variations
- Use `except (ValueError, TypeError) as e:` to handle multiple exception types in one block.
- Use `else` clause after except to run code that only executes when no exception occurs.
Real-world use cases
- Safely parsing user input from forms or command-line arguments into numbers for calculations.
- Handling API responses where fields might be missing or incorrectly formatted before further processing.
- Building a calculator or data entry application that gives friendly error messages instead of crashing.
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.