How to Handle ValueError Exceptions in Python

A beginner-friendly example showing how to catch ValueError and related exceptions with try-except blocks in Python.

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

Python code

32 lines
Python 3.9+
def divide_numbers(a, b):
    try:
        result = a / b
        return f"{a} / {b} = {result}"
    except ZeroDivisionError:
        return "Error: Cannot divide by zero."
    except TypeError:
        return "Error: Please provide numbers, not strings."
    except ValueError:
        return "Error: Invalid value detected."


def parse_integer(user_input):
    try:
        number = int(user_input)
        return f"Parsed integer: {number}"
    except ValueError:
        return f"Error: '{user_input}' is not a valid integer."
    except TypeError:
        return "Error: Input must be a string."


if __name__ == "__main__":
    print("--- Division Examples ---")
    print(divide_numbers(10, 2))
    print(divide_numbers(10, 0))
    print(divide_numbers("10", 2))

    print("\n--- Integer Parsing Examples ---")
    print(parse_integer("42"))
    print(parse_integer("hello"))
    print(parse_integer(None))

Output

stdout
--- Division Examples ---
10 / 2 = 5.0
Error: Cannot divide by zero.
Error: Please provide numbers, not strings.

--- Integer Parsing Examples ---
Parsed integer: 42
Error: 'hello' is not a valid integer.
Error: Input must be a string.

How it works

The try-except blocks catch specific exceptions raised during runtime. ZeroDivisionError triggers when dividing by zero, while TypeError catches incompatible data types. The ValueError occurs when a function receives an argument with the correct type but an invalid value, like int("hello"). Each handler returns a clear error message so the program continues instead of crashing. Multiple except clauses let you respond differently to each failure type.

Common mistakes

  • Catching the base `Exception` class instead of specific exception types.
  • Using `return` inside `except` blocks without considering the function flow.
  • Forgetting that `ValueError` and `TypeError` are distinct — wrong type vs. invalid value.
  • Not wrapping risky operations like user input parsing in try-except at all.

Variations

  1. Use `except (ValueError, TypeError)` to handle multiple exception types in one block.
  2. Add an `else` clause to run code only when no exception occurs.

Real-world use cases

  • Parsing user-provided input from CLI arguments or forms into typed values.
  • Validating configuration file values before using them in application logic.
  • Converting external API response strings into integers for database storage.

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.