Python Reference ยท Exceptions
Python ValueError
Reference for Python ValueError: what raises it, common messages such as invalid literal for int(), how to catch it, and when to raise it yourself.
ValueError is raised when a function receives an argument of the right type but an unsuitable value. The type is acceptable (a string for int()), but the content is not ("abc" is not a number).
It is one of the most common exceptions, and the right one to raise from your own code when a caller passes a value that is out of range or malformed. It derives directly from Exception; UnicodeError and json.JSONDecodeError are subclasses.
int("12.5") # ValueError: invalid literal for int() with base 10: '12.5'
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
raise ValueError("message") try: ... except ValueError as error: ...
| Name | Description |
|---|---|
message |
Optional text (or any arguments) stored in error.args. |
Raises when: a built-in operation receives a correct-typed argument with a bad value.
Usage notes
- Typical triggers:
int("x"),float("x"),list.index(missing),list.remove(missing),math.sqrt(-1),max([]), unpacking with the wrong number of targets (not enough values to unpack),random.choiceon a bad range,datetimewith a month of 13, andstr.split("")(empty separator). - ValueError vs. TypeError. Wrong kind of object (
int([])) isTypeError; right kind with a bad value (int("x")) isValueError. - ValueError vs. KeyError / IndexError. Missing lookups in dicts and sequences raise the specific lookup errors, but searching methods like
.index()raiseValueError. - Convert early. Wrap user input in
try/except ValueErrorright where you parse it, and ask again or report a clear message. - Raise it yourself for invalid arguments, with the bad value in the message.
raise ... from Nonehides an irrelevant original traceback. - Do not use it for control flow when a test is cheap:
str.isdigit()orx in itemscan avoid the exception, but the "ask forgiveness" style withtryis also idiomatic and avoids races. - Subclass it for domain errors:
class InvalidEmail(ValueError).