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.

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

Python code

21 lines
Python 3.9+
def 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

stdout
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

  1. Use `float(text)` in a separate try/except to also accept numeric strings with decimals.
  2. 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

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.