Tutorial

Python ValueError Exception Handling Examples

Practical guide to Python ValueError exception handling: causes, examples (int() conversion, math domain errors), try/except patterns, nested handling, raising ValueError, and best practices.

Drake Nguyen

Founder · System Architect

3 min read
Python ValueError Exception Handling Examples
Python ValueError Exception Handling Examples

What is ValueError in Python?

ValueError in Python occurs when a function receives an argument that has the correct type but an inappropriate value. When a more specific built-in exception isn’t suitable, Python raises ValueError to indicate the value itself is invalid. This page focuses on Python ValueError exception handling and how to diagnose and resolve common scenarios.

Common ValueError examples

Two frequent sources of ValueError are converting strings to numbers and performing math operations that require valid domains (for example, square roots of negative numbers).

Invalid literal for int()

# converting user input to int can raise ValueError
s = "abc"
try:
    n = int(s)
except ValueError as e:
    print(f"Could not convert '{s}' to int: {e}")

Math domain errors

import math

try:
    print(math.sqrt(-9))  # math.sqrt raises ValueError for negative inputs
except ValueError as e:
    print("math domain error:", e)

How to handle ValueError in Python (try/except examples)

Use try/except blocks to catch ValueError and respond gracefully. Catching ValueError directly is preferable to a bare except, since it avoids hiding unrelated errors.

import math

s = input('Enter a positive integer: ')
try:
    x = int(s)
    result = math.sqrt(x)
except ValueError as ve:
    # This handles both invalid int() conversions and math domain errors
    print('Invalid input:', ve)
else:
    print('Square root is', result)

Nested try/except for multiple failure points

When separate operations can raise ValueError for different reasons (e.g., conversion vs. math operation), a nested try/except allows you to give more specific feedback.

import math

s = input('Enter a positive integer: ')
try:
    x = int(s)
    try:
        print('Square root is', math.sqrt(x))
    except ValueError:
        print(f'ValueError: {x} is not in the domain for sqrt (must be non-negative)')
except ValueError:
    print(f"ValueError: '{s}' is not a valid integer")

Raising ValueError in your functions

When validating arguments inside a function, raise ValueError to communicate that the value is inappropriate. Use TypeError if the type itself is incorrect.

import math

def num_stats(x):
    if not isinstance(x, (int, float)):
        raise TypeError('num_stats expects a number')
    if x < 0:
        raise ValueError('num_stats expects a non-negative number')

    print(f'{x} squared is {x * x}')
    print(f'{x} square root is {math.sqrt(x)}')

# Example usage
try:
    num_stats(-5)
except (TypeError, ValueError) as e:
    print('Error:', e)

Best practices for Python ValueError exception handling

  • Catch ValueError specifically (try/except ValueError) rather than using a bare except to avoid masking other issues.
  • Validate inputs before conversion to reduce exceptions (e.g., check string contents before int()).
  • Provide clear custom messages when raising ValueError to aid debugging and logging.
  • Use nested try/except or multiple except clauses to distinguish between different error sources.
  • Prefer isinstance checks and explicit validation to decide between raising TypeError or ValueError.

Quick reference and further reading

  • Python built-in exceptions documentation: ValueError and related exception types (search "ValueError Python Docs").
  • Guides on Python try/except and input validation (search for "Python Exception Handling try/except").
Summary: Proper Python ValueError exception handling improves program robustness. Catch ValueError where appropriate, validate inputs to prevent avoidable errors, and raise clear exceptions inside functions to communicate contract violations.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.