ValueError
The type is fine but this particular value is not — int('abc'), unpacking three items into two names, math.sqrt(-1).
Demo
int('42')
In Trigger, ' -7 ' and '1_000' convert fine but '3.5' does not: int() of a str accepts only an integer literal. In Handle, note the two unpacking messages — too many values says what it expected, not enough values also says how many it got. In Raise, a str input never reaches your ValueError: 0 <= 'half' fails first with a TypeError.
Constructor
| Name | Type | Required | Description |
|---|---|---|---|
| *args | object | no | Usually one message string describing the bad value. Stored in e.args. |
Attributes
| Attribute | Type | Meaning |
|---|---|---|
| args | tuple | The constructor arguments — normally a 1-tuple holding the message. |
| __cause__ | BaseException | None | Set by raise ValueError(…) from e — keeps the original low-level error attached. |
| __notes__ | list[str] | Extra context added with e.add_note() (Python 3.11+), e.g. the line number of the bad record. |
Common patterns
def parse_int(text, default=None): try: return int(text) except ValueError: return default
def set_port(port): if not 0 < port < 65536: raise ValueError(f'port must be 1-65535, got {port}') return port
def load(lines): rows = [] for n, line in enumerate(lines, 1): try: name, qty = line.split(',') rows.append((name, int(qty))) except ValueError as e: raise ValueError(f'line {n}: {line!r}') from e return rows
from enum import Enum class Mode(Enum): READ = 'r' WRITE = 'w' mode = Mode('r')
Examples
Pitfalls
d = {'a': 1, 'b': 2} [k + str(v) for k, v in d]
d = {'a': 1, 'b': 2} [k + str(v) for k, v in d.items()]
def parse(x): try: return int(x) except ValueError: return 0 parse(None)
def parse(x): try: return int(x) except (TypeError, ValueError): return 0 parse(None)
tags = ['new'] tags.remove('sale') tags
tags = ['new'] if 'sale' in tags: tags.remove('sale') tags
When to use
- An argument has the right type but is out of range or malformed
- Parsing user input or file data that may not match the expected format
- Rejecting an unknown option name or mode string
- The argument is the wrong type entirely → TypeError
- A key or index is missing from a container → KeyError / IndexError
- Validating many fields at once → collect the problems, then raise one error listing them all
Notes
FAQ
Ask whether any value of this type could work. If no — a list where a number is needed, None — it is a TypeError. If some values of the type work but this one does not — int('abc'), math.sqrt(-1), a negative size — it is a ValueError. int() shows both: int(None) raises TypeError, int('abc') raises ValueError.