Skip to content
Tutorials Center
My learning

Topics

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.

Python
int("12.5")   # ValueError: invalid literal for int() with base 10: '12.5'

Try it

Python Common sources of ValueError

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.

Python Validating input and raising ValueError

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

Python
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.choice on a bad range, datetime with a month of 13, and str.split("") (empty separator).
  • ValueError vs. TypeError. Wrong kind of object (int([])) is TypeError; right kind with a bad value (int("x")) is ValueError.
  • ValueError vs. KeyError / IndexError. Missing lookups in dicts and sequences raise the specific lookup errors, but searching methods like .index() raise ValueError.
  • Convert early. Wrap user input in try/except ValueError right 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 None hides an irrelevant original traceback.
  • Do not use it for control flow when a test is cheap: str.isdigit() or x in items can avoid the exception, but the "ask forgiveness" style with try is also idiomatic and avoids races.
  • Subclass it for domain errors: class InvalidEmail(ValueError).