Understanding Python ValueError: Causes and Handling
Learn when Python raises ValueError, how to catch it, and how to raise it in your own code with practical examples.

The Python ValueError exception is one of the most common built-in exceptions developers encounter. It is raised when a function receives an argument of the correct type but an inappropriate value. For example, int("abc") raises ValueError because the string cannot be converted to an integer. This exception signals a semantic problem with the value passed to a function, as opposed to a type mismatch, which raises TypeError. Understanding when ValueError is raised and how to handle it is essential for writing robust Python code.
When Python Raises ValueError
Python's built-in functions and many standard library modules raise ValueError when the input value is semantically invalid, even though the type is correct. The classic example is type conversion:
int("42") # works
int("4.2") # raises ValueError: invalid literal for int() with base 10: '4.2'
float("1.2") # works
float("abc") # raises ValueError: could not convert string to float: 'abc'The same principle applies to functions that expect values within a certain range or format. For instance, math.sqrt(-1) raises ValueError because the square root of a negative number is not defined for real numbers. Similarly, list.remove(x) raises ValueError if x is not present in the list, because the value is not found.
Recognizing that ValueError is about value semantics helps you distinguish it from other exceptions. When you see ValueError in a traceback, the first thing to check is whether the argument's value violates a constraint that the function enforces.
Common ValueError Scenarios
Several everyday operations raise ValueError. Knowing these patterns helps you anticipate and handle them correctly.
String and Number Conversion
Converting strings to numbers is a frequent source of ValueError. The int() and float() constructors accept strings that represent numeric literals, but reject anything else:
def parse_number(text):
try:
return int(text)
except ValueError:
return NoneSequence Operations
Methods like list.remove() and index() raise ValueError when the target value is not found:
colors = ["red", "green", "blue"]
colors.remove("yellow") # ValueError: list.remove(x): x not in listMathematical Domain Errors
The math module raises ValueError for operations outside the function's domain. For example, math.log(0) raises ValueError because the logarithm of zero is undefined.
Unpacking and Assignment
Unpacking an iterable with an incorrect number of values raises ValueError. For instance:
a, b = [1, 2, 3] # ValueError: too many values to unpack (expected 2)This occurs because the assignment expects exactly two values but receives three.
Catching and Handling ValueError
Handling ValueError is straightforward with try/except. The key is to catch it at the right level so you can respond appropriately without masking other errors.
A common pattern is to convert a value inside a try block and then raise a more informative error if the conversion fails:
def get_port(value):
try:
port = int(value)
except ValueError:
raise ValueError(f"Invalid port number: {value}") from None
if not (0 <= port <= 65535):
raise ValueError("Port must be between 0 and 65535")
return portNotice the use of from None to suppress the original traceback when you re-raise a more specific error. This keeps the error message clear and avoids confusing the user with the internal conversion failure.
Raising ValueError in Your Own Code
When you write functions or methods that accept values with constraints, you should raise ValueError when the constraint is violated. This makes your API consistent with Python's built-in behavior and helps callers handle errors predictably.
def set_age(age):
if not isinstance(age, int):
raise TypeError("age must be an integer")
if age < 0 or age > 150:
raise ValueError("age must be between 0 and 150")
self._age = ageHere, TypeError is used for type mismatches, while ValueError is reserved for out-of-range values. This separation mirrors Python's standard library and makes your exception handling more precise.
When raising ValueError, include a clear message that explains what value was invalid and what the expected constraint is. Avoid raising ValueError for control flow; it should represent genuine invalid input, not a normal branch condition.
ValueError vs TypeError: How to Choose
A common source of confusion is deciding between ValueError and TypeError. The rule is simple: TypeError is for wrong types, ValueError is for wrong values of the correct type.
| Exception | Condition | Example |
|---|---|---|
| TypeError | Argument has the wrong type | len(5) → TypeError: object of type 'int' has no len() |
| ValueError | Argument has the correct type but an invalid value | int("abc") → ValueError: invalid literal for int() |
In your own functions, apply the same logic. If a parameter is expected to be a string but receives an integer, raise TypeError. If it is a string but its content doesn't meet the required format, raise ValueError.
Exception Handling Cost and Performance
Raising and catching exceptions in Python has a performance cost. The interpreter builds a traceback and unwinds the stack, which is more expensive than a simple conditional check. Therefore, you should not use exceptions for normal control flow, especially in performance-sensitive loops.
Consider a function that parses a list of strings into integers:
def parse_all(values):
result = []
for v in values:
try:
result.append(int(v))
except ValueError:
result.append(None)
return resultIf most strings are valid, this is fine. If invalid input is common, the exception path can be slower than a conditional check. One option is to pre-validate before converting, but any validator must match int() exactly:
def parse_or_none(text):
if text.isdigit():
return int(text)
return Nonestr.isdigit() is not a general replacement for int(); it rejects values like "-1" or "1_000" that int() accepts. Use it only when your data is known to contain non-negative plain digits. Otherwise, catching ValueError is the reliable way to parse.
ValueError in Custom Classes and Edge Cases
When you define custom classes, you can raise ValueError in methods that enforce invariants. This is especially useful for data validation in domain models. For example, a Temperature class might reject values below absolute zero:
class Temperature:
def __init__(self, celsius):
if celsius < -273.15:
raise ValueError("Temperature cannot be below absolute zero")
self.celsius = celsiusEdge cases also arise with built-in functions that accept multiple formats. For instance, int() can accept a string with a base, but only if the string contains digits valid for that base. int("0x1F", 16) works, but int("1F", 10) raises ValueError because F is not a decimal digit.
Another subtle edge case is that some functions raise ValueError only under certain conditions. For example, bytes.fromhex() raises ValueError if the input contains non-hexadecimal characters, but it also raises ValueError if the number of characters is odd. Understanding these nuances helps you write more precise error handling.
Finally, remember that ValueError is a subclass of Exception, so catching Exception will also catch ValueError. However, it is better to catch the specific exception to avoid masking unrelated errors. Always catch the narrowest exception that you can handle meaningfully.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.