How to Handle ValueError in Python (try except)

Learn to catch ValueError and other exceptions with try-except blocks in Python using practical division and string-to-float conversion examples.

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

Python code

29 lines
Python 3.10+
def divide_numbers(a, b):
    """Divide two numbers and handle ValueError safely."""
    try:
        result = a / b
        return f"{a} / {b} = {result}"
    except ZeroDivisionError:
        return "Error: Cannot divide by zero!"
    except TypeError:
        return "Error: Both inputs must be numbers!"


def parse_float(value):
    """Convert a string to float, gracefully handling bad input."""
    try:
        converted = float(value)
        return f"Converted '{value}' to {converted}"
    except ValueError:
        return f"Error: '{value}' is not a valid number!"


if __name__ == "__main__":
    # Demonstrate division cases
    print(divide_numbers(10, 2))
    print(divide_numbers(7, 0))
    print(divide_numbers(9, "3"))

    # Demonstrate parsing cases
    print(parse_float("3.14"))
    print(parse_float("hello"))

Output

stdout
10 / 2 = 5.0
Error: Cannot divide by zero!
Error: Both inputs must be numbers!
Converted '3.14' to 3.14
Error: 'hello' is not a valid number!

How it works

This example shows how try-except catches specific exceptions without crashing the program. The except ValueError block only triggers when a value cannot be converted to a float, while except ZeroDivisionError handles division by zero. Multiple except clauses let you respond to different error types individually, keeping the code robust. Control flow continues after the except block, so later code still runs. This pattern is essential for user input validation and file processing where errors are common.

Common mistakes

  • Catching Exception broadly instead of specific types, hiding bugs
  • Forgetting that float('3.14') is valid but float('3.14abc') raises ValueError
  • Not returning or raising after a caught exception, causing silent failure
  • Placing a more general except before a specific one, making it unreachable

Variations

  1. Use a `try-except-else` block to run code only when no exception occurs
  2. Catch multiple exception types in one clause with `except (ValueError, TypeError)`

Real-world use cases

  • Parsing user-entered numbers from a web form before storing them in a database.
  • Converting command-line arguments or config file strings to numeric types.
  • Handling malformed JSON or CSV values during data ingestion pipelines.

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.