Split try except ValueError handler for beginners in Python
Demonstrates how to handle ValueError and ZeroDivisionError separately using try/except blocks, with beginner-friendly examples for parsing and division.
Python code
21 linesdef parse_number(text):
try:
number = int(text)
return f"Parsed successfully: {number}"
except ValueError as error:
return f"Conversion failed: {error}"
def divide_numbers(dividend, divisor):
try:
result = dividend / divisor
return f"Division result: {result}"
except ZeroDivisionError:
return "Cannot divide by zero"
if __name__ == "__main__":
test_inputs = ["42", "abc", "3.14", ""]
for value in test_inputs:
print(parse_number(value))
print(divide_numbers(10, 2))
print(divide_numbers(10, 0))
Output
Parsed successfully: 42
Conversion failed: invalid literal for int() with base 10: 'abc'
Conversion failed: invalid literal for int() with base 10: '3.14'
Conversion failed: invalid literal for int() with base 10: ''
Division result: 5.0
Cannot divide by zero
How it works
Each try block isolates a risky operation—int() can raise ValueError, and division can raise ZeroDivisionError. Catching specific exception types lets each function return a tailored error message instead of crashing. Using as error captures the exception object so you can include its message in your output. The if __name__ == "__main__" guard makes the test code runnable directly while keeping the functions importable.
Common mistakes
- Catching a broad `Exception` instead of specific types like `ValueError`
- Forgetting to handle the case of empty strings when converting to `int`
- Raising a new exception inside `except` without re-raising the original when needed
Variations
- Use `float(text)` in a separate try/except to also accept numeric strings with decimals.
- Add a `finally` block to log cleanup actions regardless of success or failure.
Real-world use cases
- Parsing user input from CLI arguments or forms, returning friendly errors instead of crashing.
- Validating configuration values read from environment variables before using them.
- Handling division in a calculator app, gracefully prompting the user when zero is entered.
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.